插件定义
export const LazyLoadPlugin = {
//如果没有写options参数,一定要将options赋与初始值,不然会报读取null的属性错误
install(app,options = {}){
//代替图片的loading图
let defaultSrc = options.default
app.directive('lazy',{
mounted(el,binding){
LazyLoadPlugin.init(el,binding.value,defaultSrc)
if('IntersectionObserver' in window){
LazyLoadPlugin.observe(el)
}else {
LazyLoadPlugin.listenerScroll(el)
}
}
})
},
//初始化
init(el,val,def){
//data-src存储真实的src
el.setAttribute('data-src',val)
//设置src为loading图
el.setAttribute('src',def)
},
//利用IntersectionObserver监听el
observe(el){
let io = new IntersectionObserver( entries=>{
let realSrc = el.dataset.src;
if(entries[0].isIntersecting){
if(realSrc){
el.src = realSrc
el.removeAttribute('data-src')
}
}
})
io.observe(el)
},
//监听scroll事件
listenerScroll(el){
let handler = LazyLoadPlugin.throttle(LazyLoadPlugin.load,300)
LazyLoadPlugin.load(el)
window.addEventListener('scroll',()=>{
handler(el)
})
},
//加载真实图片
load(el){
let windowHeight = document.documentElement.clientHeight
let elTop = el.getBoundingClientRect().top
let elBtm = el.getBoundingClientRect().bottom
let realSrc = el.dataset.src
if(elTop - windowHeight < 0 && elBtm > 0){
if(realSrc){
el.src = realSrc
el.removeAttribute('data-src')
}
}
},
//节流,时间戳写法
throttle(fn,delay){
let timer
let prevTime
return function(...args){
let currTime = Date.now()
let context = this
if(!prevTime){
prevTime = currTime
}
clearTimeout(timer)
if(currTime - prevTime > delay){
prevTime = currTime
fn.apply(context,args);
clearTimeout(timer)
return
}
timer = setTimeout(()=>{
prevTime = Date.now()
timer = null
fn.apply(context,args)
},delay)
}
}
}
插件注册
//第二个参数为options,并有default属性
app.use(LazyLoadPlugin,
{default:'https://img.zcool.cn/community/0196fa582abab6a84a0d304f899eaf.gif'})