//懒加载
window.onload = function(){
var imgs = Array.from(document.querySelectorAll(‘img‘));
delay();
window.addEventListener(‘scroll‘, exec(delay, 4000));
function exec(fun, delaytime){
var timeout,startTime = new Date();
return function(){
clearTimeout(timeout);
tiemout = setTimeout(fun, delaytime);
}
}
function delay(){
var scrollTop = window.scrollY;
var clientHeight = document.documentElement.clientHeight;
//console.log(clientHeight);
imgs.forEach((item, index)=>{
if(scrollTop==0 && item.offsetTop<=clientHeight+scrollTop){
//console.log(item.getAttribute(‘data_img‘));
item.setAttribute(‘src‘,item.getAttribute(‘data_img‘));
}else if(item.offsetTop<=clientHeight+scrollTop && item.offsetTop > scrollTop){
item.setAttribute(‘src‘,item.getAttribute(‘data_img‘));
}
});
}
}
//预加载
var target = document.getElementById(‘test‘);
addImg(‘./2.jpg‘);
function addImg(url){
var img = document.createElement(‘img‘);
var image = new Image();
image.src=url;
image.onload = function(){
img.src = this.src;
img.height = 50;
img.width = 50;
}
target.appendChild(img);
}
//html
<div id="test"></div>
原文:https://www.cnblogs.com/connie313/p/13619893.html