(function(){
function LazyImage(options){
// init params
options = options || {};
let defaults = {
context:document,
attr:'lazy-image',
threshold:1,
speed:300,
callback:Function.prototype
}
return new LazyImage.prototype.init(Object.assign(defaults,options));
}
LazyImage.prototype = {
constructor:LazyImage,
init:function(config){
// 把信息挂载到 实例上
this.config = config;
this.imageBoxList = [];
// 创建监听器
const oboptions = {
threshold:[config.threshold]
};
this.ob = new IntersectionObserver(changes => {
changes.forEach(item=>{
let {isIntersecting,target} = item;
if(isIntersecting){
this.singleHandle(target);
// 移除监听
this.ob.unobserve(target);
}
})
},oboptions);
this.observeAll();
},
// 单张图片的加载
singleHandle:function(imgObx){
let config = this.config,
imgObj = imgObx.querySelector('img'),
trueImg = imgObj.getAttribute(config.attr);
imgObj.src = trueImg;
// 移除已经加载过的图片
imgObj.removeAttribute(config.attr);
imgObj.onload = () => {
imgObj.style.transition=`opacity ${config.speed}ms`;
imgObj.style.opacity = 1;
// 回调函数->生命周期函数[回调函数/发布订阅]
config.callback.call(this,imgObj);
}
},
// 监听所有 DOM 元素
observeAll(refresh){
let config = this.config,
allImages = config.context.querySelectorAll(`img[${config.attr}]`);
[].forEach.call(allImages,item=>{
let imgBox = item.parentNode;
//判断如果已经存在 就不需要再次监听
if(refresh && this.imageBoxList.includes(imgBox)) return;
this.imageBoxList.push(imgBox);
this.ob.observe(imgBox);
})
},
// 刷新: 获取新增的需要延迟加载的图片,做延迟加载
refresh:function(){
this.observeAll(true);
}
}
LazyImage.prototype.init.prototype = LazyImage.prototype;
if(typeof window !=="undefined"){
window.LazyImage = LazyImage;
}
if(typeof module === "object" && typeof module.exports === 'object'){
module.exports = LazyImage;
}
})();