用法:Lazyload.load([time])
Lazyload = {
lazyCheck: null, // 延时检测
imgs: [], // 匹配的图片
/**
* ¸初始化,可选参数
* @param {number} lazy 延迟多久加载,超时则不加载,默认 250ms
*/
load(lazy) {
const nodes = document.querySelectorAll('img')
this.lazy = lazy || 250
// nodeList 转 array
for (let i = 0; i < nodes.length; i++) {
this.imgs.push(nodes[i])
}
this.check()
const check = this.check.bind(this)
if (document.addEventListener) {
window.addEventListener('scroll', check, false)
} else {
window.attachEvent('onscroll', check)
}
},
/**
* 检查是否可视
*/
check() {
clearTimeout(this.lazyCheck)
let showImgs = this.showImgs.bind(this)
this.lazyCheck = setTimeout(showImgs, this.lazy)
},
/**
* 尝试显示
*/
showImgs() {
for (let i = this.imgs.length; i--;) {
const img = this.imgs[i]
if (this.canSee(img)) {
img.src = img.getAttribute('data-il')
this.imgs.splice(i, 1)
}
}
},
/**
* 是否在可视区域内
* @param {DOM} img 检查元素
*/
canSee(img) {
const coords = img.getBoundingClientRect()
return (coords.top <= window.innerHeight) && coords.bottom >= 0 // 顶部距离大于窗口宽度则在下面看不见,底部距离小于 0,则在窗口上面看不见,这里取反就是可见
}
}