//自定义图片懒加载组件 start
var lazyLoad = {
lazyLoadCache: [],//储存已经加载过的图片
layLoadList: [],//储存没有加载过的图片
throttleDuration: 500,//节流定时器延时
clientHeight: window.innerHeight || document.documentElement.clientHeight,
install: function(){
lazyLoad.create();
},
create: function(){
var self = this;
this.initScrollEvent();
Vue.directive('lazyload', {
inserted: function(el, bind){
self.init(el, bind);
},
updated: function(el, bind){
self.init(el, bind);
}
})
},
init: function(el, bind){
var imgUrl = bind.value;
el.targeUrl = imgUrl;
lazyLoad.layLoadList.push(el);
var mark = !lazyLoad.isLoaded(el);//判断是否可以加载
showMark = mark && lazyLoad.isCanShow(el);
showMark && lazyLoad.showImg(el, imgUrl);
},
initScrollEvent: function(el){
var self = this,
timer = 0,
duration = this.throttleDuration,
toShowImgFun = this.toShowImg,
documentElement = document.documentElement,
startTop = documentElement.scrollTop;
window.addEventListener('scroll', handleScrolEl())
function handleScrolEl(){//判断是向上滚动还是向下滚动
//使用函数节流
var nowTime = Date.now();
return function(){
var currentTime = Date.now(),
currentTop = documentElement.scrollTop || document.body.scrollTop;
if(currentTop - startTop <= 0){//向上滚动不处理
return;
}
var remaining = currentTime - nowTime;
if( duration <= remaining){//如果间隔时间大于延时,执行函数
clearTimeout(timer);
nowTime = Date.now();
toShowImgFun.call(self);
startTop = documentElement.scrollTop;
}else {
timer = setTimeout(toShowImgFun.call(self), duration);
}
}
}
},
toShowImg: function(){
var self = this,
layLoadList = this.layLoadList;
if(layLoadList.length <= 0){//预加载图片加载完毕
return;
}
layLoadList.map(function(item){
!self.isLoaded(item) && self.isCanShow(item) && self.showImg(item, item.targeUrl);
})
},
//判断是否能够显示
isCanShow: function(el){
var top = el.getBoundingClientRect().top,
windowHeight = this.clientHeight;
return top + el.height / 2 < windowHeight;
},
//判断是否已经加载过了
isLoaded: function(img){
var lazyLoadCache = this.lazyLoadCache;
return lazyLoadCache.indexOf(img) > -1;
},
//展示图片
showImg: function(el, imgSrc){
var self = this;
var image = new Image();
image.src = imgSrc;
image.onload = function(){
el.src = imgSrc;
self.lazyLoadCache.push(imgSrc);
self.spliceImg(imgSrc);
}
},
//从未展示的数组中剔除已经展示的图片
spliceImg: function(imgSrc){
var newList = [];
newList = this.layLoadList.filter(function(item, index){
return item.src != imgSrc;
})
this.layLoadList = newList;
}
}
//自定义图片懒加载组件 end
网友评论