直接上源代碼:this
export default (Vue , options = {})=>{ if(!Array.prototype.remove){ Array.prototype.remove = function(item){ if(!this.length) return var index = this.indexOf(item); if( index > -1){ this.splice(index,1); return this } } } var init = { lazyLoad: false, default: '/static/img/yes.png' } var listenList = []; var imageCatcheList = []; const isAlredyLoad = (imageSrc) => { if(imageCatcheList.indexOf(imageSrc) > -1){ return true; }else{ return false; } } //檢測圖片是否能夠加載,若是能夠則進行加載 const isCanShow = (item) =>{ var ele = item.ele; var src = item.src; //圖片距離頁面頂部的距離 var top = ele.getBoundingClientRect().top; //頁面可視區域的高度 var windowHeight = window.innerHight; //top + 10 已經進入了可視區域10像素 if(top + 10 < window.innerHeight){ var image = new Image(); image.src = src; image.onload = function(){ ele.src = src; imageCatcheList.push(src); listenList.remove(item); } return true; }else{ return false; } }; const onListenScroll = () =>{ window.addEventListener('scroll',function(){ var length = listenList.length; for(let i = 0;i<length;i++ ){ isCanShow(listenList[i]); } }) } //Vue 指令最終的方法 const addListener = (ele,binding) =>{ //綁定的圖片地址 var imageSrc = binding.value; //若是已經加載過,則無需從新加載,直接將src賦值 if(isAlredyLoad(imageSrc)){ ele.src = imageSrc; return false; } var item = { ele:ele, src:imageSrc } //圖片顯示默認的圖片 ele.src = init.default; //再看看是否能夠顯示此圖片 if(isCanShow(item)){ return } //不然將圖片地址和元素均放入監聽的lisenList裏 listenList.push(item); //而後開始監聽頁面scroll事件 onListenScroll(); } Vue.directive('lazyload',{ inserted:addListener, updated:addListener }) }
調用方法:prototype
import LazyLoad from 'lazyLoad.js' Vue.use(LazyLoad);