图片懒加载比较适合用函数节流
如果利用函数防抖,那么加载过程中页面一直空白也不合适
<template>
<div class="home">
<ul>
<li v-for="(item, index) in 9" :key="index">
<!-- <img src="@/assets/img/1.jpg" alt="" /> -->
<img
ref="imgs"
src="@/assets/wode.png"
:data-src="require('@/assets/img/' + (index + 1) + '.jpg')"
alt
/>
</li>
</ul>
</div>
</template>
export default {
data() {
return {};
},
mounted() {
this.init();
},
methods: {
init() {
let self = this;
window.onscroll = self.throttle(function (e) {
self.loadImg();
});
},
//函数节流 过一段时间执行一次
throttle(func, delay = 500) {
let isRun = true;
return function () {
if (!isRun) {
return;
}
isRun = false;
setTimeout(() => {
func.apply(this, arguments);
isRun = true;
}, delay);
};
},
//防抖 操作结束之前一直不执行
debounce(func, delay = 300) {
let timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, arguments);
}, delay);
};
},
//只有当图片距离顶部小于可视窗口的高度时才加载图片
loadImg() {
let imgs = this.$refs.imgs;
imgs.forEach((item) => {
let y = item.getBoundingClientRect().top;
if (y < window.innerHeight) {
item.src = item.dataset.src;
}
});
},
},
};
网友评论