一、html(这里只列出相关的结构,body那些就不列了~)
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<img class="imgLazyLoad" data-src="http://office.qq.com/images/title.jpg" />
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
其中,img标签就是我们今天的主角,data-src属性上面保存着我们后面需要动态加载的图片地址,初始化时图片没有设置任何链接~
二、js(css就略过了)
(function(){//立即执行函数
let imgList = [],delay,time = 250,offset = 0
function _delay(){//函数节流
clearTimeout(delay)
delay = setTimeout(() => {
_loadImg()
},time)
}
function _loadImg(){//执行图片加载
for(let i = 0,len = imgList.length
if(_isShow(imgList[i])){
imgList[i].src = imgList[i].getAttribute('data-src')
imgList.splice(i,1)
}
}
}
function _isShow(el){//判断img是否出现在可视窗口
let coords = el.getBoundingClientRect()
return (coords.left >= 0 && coords.left >= 0 && coords.top) <= (document.documentElement.clientHeight || window.innerHeight) + parseInt(offset)
}
function imgLoad(selector){//获取所有需要实现懒加载图片对象引用并设置window监听事件scroll
_selector = selector || '.imgLazyLoad'
let nodes = document.querySelectorAll(selector)
imgList = Array.apply(null,nodes)
window.addEventListener('scroll',_delay,false)
}
imgLoad('.imgLazyLoad')
})()