HTML
<img src="http://temp.im/110x110" data-src="src" alt="" >
JS
watch: {
$route: {
handler(val, oldVal) {
// 监听组件dom加载完成
this.$nextTick(() => {
// 加载首屏
this.imgLazyLoading()
window.addEventListener('scroll', () => {
this.imgLazyLoading()
})
})
},
deep: true
}
},
methods: {
/**
* 全局图片懒加载
*/
imgLazyLoading() {
const seeHeight = document.documentElement.clientHeight // 获取可视区域高度
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop // 获取已经滑动区域的高度
document.querySelectorAll('img').forEach(el => {
if (el.attributes['data-src'] && el.src !== el.attributes['data-src'].nodeValue) {
if (el.offsetTop < seeHeight + scrollTop - 100) {
var img = document.createElement('img')
const src = el.src
img.src = el.attributes['data-src'].nodeValue
img.onload = (e) => {
el.src = el.attributes['data-src'].nodeValue
}
img.onerror = (e) => {
el.attributes['data-src'].nodeValue = src
}
}
}
})
}
}
网友评论