1.懒加载概念
对于页面有很多静态资源的情况下(比如网商购物页面),为了节省用户流量和提高页面性能,可以在用户浏览到当前资源的时候,再对资源进行请求和加载。
2.懒加载实现原理
2.1监听onscroll事件判断资源位置
首先为所有懒加载的静态资源添加自定义属性字段,比如如果是图片,可以指定data-src为真实的图片地址,src指向loading的图片。
然后当资源进入视口的时候,将src属性值替换成data-src的值。
可以使用元素的getBoundingRect().top判断是否在视口内,也可以使用元素距离文档顶部的距离offsetTop和scrollTop是否小于视口高度来判断:
window.function(){
var clientHeight=getWindow().height;
//选取所有包含属性data-src的img元素,然后在滚动的时候判断是否在可视区域
var imgArray=toArray(document.querySelectorAll("[data-src]"));
function lazyLoad(){
var loadedIndex=[];
var scrollTop=document.body.scrollTop||document.documentElement.scrollTop;
for(let i=0;i<imgArray.length;i++){
let img=imgArray[i];
if(img.offsetTop-scrollTop<clientHeight){
img.src=img.getAttribute("data-src");
console.log("img "+img.src.substring(img.src.lastIndexOf("/")+1)+"display.");
loadedIndex.unshift(i);//这里不能用push,因为删除的时候先要删除后面的,再删除前面的,否则Array删除了前面的,后面的就会自动覆盖到前面来。
}
}
for(let i=0;i<loadedIndex.length;i++){
imgArray.splice(loadedIndex[i],1);
}
}
//跨浏览器获取可视窗口大小
function getWindow () {
if(typeof window.innerWidth !='undefined') {
return{
width : window.innerWidth,
height : window.innerHeight
}
} else{
return {
width : document.documentElement.clientWidth,
height : document.documentElement.clientHeight
}
}
}
function toArray(arrlike){
if(typeof Array.from !="function"){
var result=[];
for(let i=0;i<arrlike.length;i++){
result.push(arrlike[i]);
}
return result;
}else{
return Array.from(arrlike);
}
}
window.onscroll=lazyLoad;
lazyLoad();
}
其中判断元素是否应该下载的语句是:
if(img.offsetTop-scrollTop<clientHeight){
img.src=img.getAttribute("data-src");
console.log("img "+img.src.substring(img.src.lastIndexOf("/")+1)+"display.");
loadedIndex.unshift(i);
}
或者是:
if(rect.top>=0&&rect.top<=clientHeight)
但是由于scroll事件密集发生,计算量很大,容易造成性能问题,因此不推荐使用。