实现图片懒加载
在项目中,有时候一个页面会有很多张图片展示,可是页面加载时候如果图片过多或者图片的体积过大就会影响页面的加载速度,这时候用户体验就不太好,所以可以对图片进行懒加载处理。
实现代码
<template>
<div class="img-load">
<ul>
<li v-for="(item, index) in imgList" :key="index">
<img src="../../assets/imgLoad/default.jpg" alt="" :data-src="item.url">
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
imgList: [{
url: require('../../assets/imgLoad/1.jpg')
}, {
url: require('../../assets/imgLoad/2.jpg')
}, {
url: require('../../assets/imgLoad/3.jpg')
}, {
url: require('../../assets/imgLoad/4.jpg')
}, {
url: require('../../assets/imgLoad/5.jpg')
}, {
url: require('../../assets/imgLoad/6.jpg')
}, {
url: require('../../assets/imgLoad/7.jpg')
}, {
url: require('../../assets/imgLoad/8.jpg')
}, {
url: require('../../assets/imgLoad/9.jpg')
}, {
url: require('../../assets/imgLoad/10.jpg')
}]
}
},
created() {
this.$nextTick(()=>{
this.lazyLoadImage()
})
window.addEventListener('scroll', this.throttle(this.lazyLoadImage, 200))
},
methods: {
// 获取浏览器的可视区高度;获取所有的图片的dom,获取到图片的top值,遍历判断当前的图片是否都到了可视区范围
lazyLoadImage() {
let viewHeight = document.body.clientHeight
let imgs = document.querySelectorAll('img[data-src]')
imgs = [...imgs]
imgs.forEach((item, index) => {
if (item.dataset.src === '') return
// 获取页面中的某个元素的上下左右分别对应浏览器视口区的位置
let pos = item.getBoundingClientRect()
console.log('pos', pos)
if(pos.bottom >= 0 && pos.top < viewHeight) {
item.src = item.dataset.src
item.removeAttribute("data-src")
}
});
},
// 节流
throttle(fn, delay) {
let timer = null
let prevTime = null
return function (...args) {
const currTime = Date.now()
const context = this
if (!prevTime) prevTime = currTime
clearTimeout(timer)
if (currTime - prevTime > delay) {
prevTime = currTime
fn.apply(context, args)
clearTimeout(timer)
return
}
timer = setTimeout(function () {
prevTime = Date.now()
timer = null
fn.apply(context, args)
}, delay)
}
}
}
}
</script>
<style scoped lang="scss">
.img-load {
ul {
li {
img {
width: 400px;
height: 400px;
}
}
}
}
</style>