图片懒加载简单来说是指进入页面时非可视区域的图片不加载,目的是提高渲染速度
直接上代码
<template>
<div class="lazy">
<img v-lazy="item" width="300px" height="400px" v-for="(item, i) in arrList" :key="i" src="">
</div>
</template>
let arrList = [
'https://tse3-mm.cn.bing.net/th/id/OIP-C.PblErH34r4TZEYtrIHP2bAAAAA?w=187&h=333&c=7&r=0&o=5&pid=1.7',
'https://tse1-mm.cn.bing.net/th/id/OIP-C.cqwDlCQ63kidK9qoKK_GkwHaNK?w=187&h=333&c=7&r=0&o=5&pid=1.7',
'https://tse2-mm.cn.bing.net/th/id/OIP-C.6ohtlagu9z-P-vXPaxnthQHaLG?w=204&h=306&c=7&r=0&o=5&pid=1.7',
'https://tse1-mm.cn.bing.net/th/id/OIP-C.Qp74PrYLkMGMIkTehqTdnwHaLG?w=204&h=306&c=7&r=0&o=5&pid=1.7',
]
存放图片地址的数组,通过v-for渲染到页面
const vLazy: Directive = async (el, binding) => {
const logo = await import('@/assets/logo.svg')
el.src = logo.default
const watchItem = new IntersectionObserver((entries) => {
// intersectionRatio 指 当前元素占据视窗比例 0-1
if (entries[0].intersectionRatio > 0) {
// 大于0说明已出现在视窗,可以展示
el.src = binding.value
// 结束监听
watchItem.unobserve(el)
}
})
watchItem.observe(el)
}
IntersectionObserver
接口(从属于 Intersection Observer API)提供了一种异步观察目标元素与其祖先元素或顶级文档视口(viewport)交叉状态的方法。其祖先元素或视口被称为根(root)当一个
IntersectionObserver
对象被创建时,其被配置为监听根中一段给定比例的可见区域。一旦IntersectionObserver
被创建,则无法更改其配置,所以一个给定的观察者对象只能用来监听可见区域的特定变化值;然而,你可以在同一个观察者对象中配置监听多个目标元素
属性 | 属性说明 |
---|---|
boundingClientRect | 返回包含目标元素的边界信息 |
intersectionRatio | 返回目标元素出现在可视区的比例,范围0~1 |
intersectionRect | 用来描述root和目标元素的相交区域 |
isIntersecting | 返回一个布尔值,两种操作均会触发callback: 1. 目标元素出现在root可视区,返回true 2. 从root可视区消失,返回false |
rootBounds | 用来描述交叉区域观察者(intersection observer)中的根 |
target | 目标元素:与根出现相交区域改变的元素 (Element) |
time | 返回一个记录从 IntersectionObserver 的时间原点到交叉被触发的时间的时间戳 |