可视区域、页面优化、DOM节点多、图片懒加载、性能
可视区域
是一个前端优化常常出现的名词,无论是显示器、手机、平板它们的可视区域
范围都是有限。在这个 有限可视区域
区域里作到完美显示和响应,而在这个区域外少作一些操做来减小渲染的压力、网络请求压力。在 每日 30 秒之 对海量数据进行切割 中的使用场景,咱们就是利用了 有限可视区域
只渲染一部分 DOM 节点来减小页面卡顿。javascript
既然
可视区域
这么重要是否有什么速成秘籍来帮咱们?
控制住每个元素在可视区域
的出现,就能够扼住命运的后颈随心所欲:css
// 该源码来自于 https://30secondsofcode.org const inViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; };
使用 Element.getBoundingClientRect 方法返回元素的大小及其相对于视口的位置,能够获得当前元素相对 可视区域
的坐标:html
const { top, left, bottom, right } = el.getBoundingClientRect();
获得元素的坐标信息后,就须要得到 可视区域
的宽高来帮助咱们肯定是否在范围内:前端
const { innerHeight, innerWidth } = window;
先判断是否须要整个元素都出如今 可视区域
:java
if (partiallyVisible) { // 只须要出如今可视区域 } else { // 须要整个元素都在可视区域内 }
判断元素头部或者底部是否在 可视区域
出现:git
(top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)
判断元素左部或者右部是否在 可视区域
出现:github
(left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)
当须要整个元素都出如今屏幕的时候,须要同时判断四个相对坐标:segmentfault
top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth
如今网页中常常会出现大量的图片,然而加载大量图片会影响网页加载速度,咱们能够利用 可视区域
来实现图片的懒加载。为何要懒加载图片:服务器
七牛云
。影子域名
来绕过这个限制。可视区域
当移动到某个 标志元素
时再进行更多数据和图片的加载。可视区域
加载部分数据图片节省网络流量。<div class="container"> <div class="img-box img-placeholder" data-src="http://suo.im/5p9IOS"></div> <div class="img-box img-placeholder" data-src="http://suo.im/5p9IOS"></div> <div class="img-box img-placeholder" data-src="http://suo.im/5p9IOS"></div> <div class="img-box img-placeholder" data-src="http://suo.im/5p9IOS"></div> <div class="img-box img-placeholder" data-src="http://suo.im/5p9IOS"></div> <div class="img-box img-placeholder" data-src="http://suo.im/5p9IOS"></div> </div>
.img-box { width: 200px; height: 200px; margin: 10px 0 10px 10px; background: #eee; display: inline-block; } .img-box > img { width: 100%; height: 100%; }
document.addEventListener('scroll', lazyLoading) window.onload = () => lazyLoading() function lazyLoading() { const boxs = document.querySelectorAll('.img-placeholder') Array.from(boxs).map(box => { if (!inViewport(box, true)) return; // 获取图片地址并清除数据记录 const src = box.getAttribute('data-src'); box.removeAttribute('data-src'); // 插入图片 DOM box.innerHTML = `<img src='${src}'>`; // 去除占位 class box.className = box.className.replace('img-placeholder', '') }) }
在困惑的城市里总少不了并肩同行的
伙伴
让咱们一块儿成长。
点赞
。小星星
。m353839115
。本文原稿来自 PushMeTop