let imageList = [...document.querySelectorAll('img')];
let num = imageList.length;
let lazyLoad1 =(()=>{
let count = 0;
return function(){
let newArr = [];
imageList.forEach((item, index) =>{
let rect = item.getBoundingClientRect();
if(rect.top < window.innerHeight){
rect.src = rect.dataset.src;
newArr.push(index);
count++;
if(count === num){
document.removeEventListener('scroll', lazyLoad1);
}
}
});
//删除已加载完的图片
imagelist = imageList.filter( (_ , index) => !newArr.includes(index))
}
})();
//在这里调用throttle的节流函数
lazyLoad1 = Proxy(lazyLoad1, 100);
document.addEventListener('scroll', lazyLoad1);
//手动执行一次,加载首屏图片
lazyLoad1();
网友评论