懒惰的道路是什么
图像的延迟加载。 许多图像在不需要加载页面时加载,当用户滑动到该视图时加载图像,以避免在打开网页时加载过多的资源。
如果页面一次加载很多资源,则经常需要懒惰的加载
图像加载原理
img标记具有src属性,如果src不为空,浏览器将根据此值发送请求
懒惰加载的实现思路
首先,在temp-src中临时保存src属性,然后在您要加载图像时将temp-src分配给src
代码实现
首先是简单的html结构
获取和确定文档中元素的位置、滚轮的旋转距离和视图的大小。
根据文档中top滚轮滚动的距离视图的大小加载图像
文档中元素的位置: element.offsetTop
滚轮滚动的距离: document.documentelement.scroll top (ie和火狐)/document.body.scrool top (chrome ) )。
显示大小:window.innerheight(ie不可用)/document.documentelement.clientheight ) ) ie下为浏览器可显示部分的高度/Chrome下为浏览器
let imglist=array.from (document.getelementbyid (' imgouter ' ).children );
//可加载区域=当前屏幕高度滚动条滚动的高度
const hasheight=function (() ) )。
const clientheight=window.innerheight;
const top=document.documentelement.scroll top|| document.body.scroll top;
return clientHeight top;
}
//判断是否加载图像,如果要加载就加载
const loadImage=function (
imglist.Foreach(div={
const img=div.children[0];
if (! img.src div.offsetTop hasheight (
//加载图像
img.src=img.attributes [ ' temp-src ' ].value;
}
);
}
//确定是否需要实时拦截滚轮幻灯片并加载图像
window.onscroll=function
loadImage (;
}
//首页画面加载
loadImage (;