The following code
function isPassive() {
let supportsPassiveOption = false
try {
addEventListener("test", null, Object.defineProperty({}, 'passive', {
get: function () {
supportsPassiveOption = true}})); } catch(e) {}return supportsPassiveOption //{passive: true} const lazyLoad = {ticking:false,
timer: null,
complete: false, position: {top: 0, // Element distance from the top right: 0, // element distance from the right bottom: 0, // element distance from the bottom left: 0: 0 // element distance left}, list: [], init (el, bingind, vnode) {this.list.push(el) this.scrollload ()}, /** * scrollLoad image display instead of default image */scrollLoad () {
if(! this.list.length && this.complete) { this.removeLazyLoad() }else {
this.ticking = false
this.list.forEach((el) => {
if(el.dataset.LazyLoadImgState ! ='success' && this.getClientRect(el, this.position)) {
this.loadImg(el)
}
})
}
},
scrollImg () {
if(! this.ticking) { this.ticking =truethis.timer = window.requestAnimationFrame(this.scrollLoad.bind(this)) } }, /** * @param {Object} el * @param {Object} options * @returns {Boolean} */ getClientRect (el,options) { const bcr = El.getboundingclientrect () const mw = el.offsetwidth // Element width const mh = el.offsetheight // element height const w H = window.innerHeight // Window height const boolX = (! ((bcr.right - options.left) <= 0 && ((bcr.left + mw) - options.left) <= 0) && ! ((bcr.left + options.right) >= w&& (bcr.right + options.right) >= (MW + W))) ((bcr.bottom - options.top) <= 0 && ((bcr.top + mh) - options.top) <= 0) && ! ((bcr.top + options.bottom) >= h && (bcr.bottom + options.bottom) >= (mh + H))returnel.width ! = 0 && el.height ! = 0 && boolX && boolY }, /** * @param {Object} el * @param {Number} index */ loadImg (el) { const imgUrl = el.dataset.src el.dataset.LazyLoadImgState ='start'
if (imgUrl) {
const img = new Image()
img.src = imgUrl
img.addEventListener('load', () = > {setTimeout(() => {
el.style.backgroundImage = 'url('+imgUrl+') '
el.style.backgroundSize = '100% auto'
delete el.dataset.src
el.dataset.LazyLoadImgState = 'success'
el.classList.add('ui-successImg')
this.list.forEach((item, index) => {
if (item == el) {
this.list.splice(index, 1)
}
})
if(! this.list.length) { this.complete =true}}}, 310),false)
img.addEventListener('error', () => {
delete el.dataset.src
el.dataset.LazyLoadImgState = 'error'
}, false)}else {
delete el.dataset.src
}
},
start () {
window.addEventListener('scroll', this.scrollImg.bind(this), isPassive() ? {passive: true, capture: true} : true)},removeLazyLoad () {
cancelAnimationFrame(this.timer)
window.removeEventListener('scroll', this.scrollImg.bind(this), isPassive() ? {passive: true, capture: true} : true)
}
}
lazyLoad.start()
Vue.directive('lazy', {
inserted (el, binding, vnode) {
lazyLoad.init(el, binding, vnode)
}
})Copy the code
Use the following
v-lazy :data-src="item"Copy the code