咳咳,每天都要学一点,尽管每天闲的🥚疼,也要学一点。
当你在做懒加载时,不会还停留在if(imgs[i].offsetTop < html.scrollTop + html.clientHeight){ .....}吧???
那么传统的懒加载通常都是基于页面滚动事件 onsrcoll
本帅比感觉这样做有两个缺点:
1、第一是滚动事件本身会造成页面性能下降,最好的是在srcoll加上防抖,但是会感觉这个过程不是很流畅。
2、只有页面滚动时才会被触发,有的小可爱用户,会让你以此之上,添加被加载后的图片再此被渲染为缓存图...
so,为了一劳永逸,为了方便后续的使用,可以使用vue(2)的自定义指令。
import defaultimg from "@/assets/logo.png"
console.log(defaultimg);
export default{
inserted(el){
const imgSrc = el.src;
el.src = ''
// 定义一个观察者;
const observe = new IntersectionObserver((
[{isIntersecting}]
)=>{
if(isIntersecting){
//加载图片
setTimeout(() => {
el.src = imgSrc;
}, 200);
// 停止观察
observe.unobserve(el)
}else{
el.src = defaultimg
}
})
observe.observe(el)
}
}
怎么使用呢?简单案例..
<template>
<div class='container'>
<li v-for="(item,index) in imglist" :key="index">
<img :src="item.img" alt="" style="width:300px;height: 300px;" v-lazyimg>
</li>
</div>
</template>
<script>
export default ({
data() {
return {
imglist:[
{img:"https://img1.baidu.com/it/u=3184485295,1843016893&fm=253&fmt=auto&app=138&f=JPEG?w=501&h=500"},
{img:"https://img1.baidu.com/it/u=3184485295,1843016893&fm=253&fmt=auto&app=138&f=JPEG?w=501&h=500"},
{img:"https://img1.baidu.com/it/u=3184485295,1843016893&fm=253&fmt=auto&app=138&f=JPEG?w=501&h=500"},
......自己补充
]
}
},
methods: {},
computed: {},
mounted() { }
})
</script>
<style lang='scss' scoped>
.container {
width: 100%;
height: 100%;
}
</style>
当你离开页面一会后,再回去会发现,之前被加载的图片也已经回到了缓存时了。