js-IntersectionObserver(懒加载)
1. API
使用方法
// 创建实例
const io = new IntersectionObserver(callback, option)
IntersectionObserver 是浏览器原生提供的构造函数,接受两个参数:callback 是可见性变化时的回调函数,option 是配置对象(该参数可选)。
构造函数的返回值是一个观察器实例。实例的observe方法可以指定观察哪个 DOM 节点。
// 开始观察
io.observe(document.querySelector('#special')
// 停止观察
io.unobserve(element)
// 关闭观察器
io.disconnect()
observe方法的参数是一个 dom 节点,如果需要观察多个对象,则需要多次调用。
io.observe(elementA)
io.observe(elementB)
2. callback 函数
当观察对象发生变化时,就会触发 callback 函数
const io = new IntersectionObserver((entries) => {
console.log(entries)
})
callback 函数的参数(entries)是一个数组,每个成员都是一个 IntersectionObserverEntry 对象。如果同时有两个被观察的对象的可见性发生变化,entries 数组就会有两个成员。
3. IntersectionObserverEntry 对象
{
boundingClientRect: { // 目标元素的矩形区域的信息
bottom: 156.4375
height: 21
left: 394
right: 527
top: 135.4375
width: 133
x: 394
y: 135.4375
}
intersectionRatio: 0 // 目标元素的可见比例,即intersectionRect占boundingClientRect的比例,完全可见时为1,完全不可见时小于等于0
intersectionRect: { // 目标元素与视口(或根元素)的交叉区域的信息
// ...
}
isIntersecting: false
isVisible: false // 是否可见
rootBounds: { // 根元素的矩形区域的信息,getBoundingClientRect()方法的返回值,如果没有根元素(即直接相对于视口滚动),则返回null
// ...
}
target: p#special // 被观察的目标元素,是一个 DOM 节点对象
time: 2491 // 可见性发生变化的时间,是一个高精度时间戳,单位为毫秒
}
4. option 对象
option: {
threshold:[0.5],
root:element,
rootMargin:'100px'
}
4.1 threshold 属性
threshold 属性决定了什么时候触发回调函数。它是一个数组,每个成员都是一个门槛值,默认为[0],即交叉比例(intersectionRatio)达到 0 时触发回调函数。
4.2 root 属性,rootMargin 属性
root 属性指定目标元素所在的容器节点(即根元素)
rootMargin 属性定义根元素的 margin,用来扩展或缩小 rootBounds 这个矩形的大小,从而影响 intersectionRect 交叉区域的大小。它使用 CSS 的定义方法,比如 10px 20px 30px 40px,表示 top、right、bottom 和 left 四个方向的值。
5. 懒加载
前端优化-懒加载:目标元素进入视口时才加载,这样可以节省带宽,提高网页性能
下面实现一个简单的图片懒加载
// 获取dom元素
const special = document.querySelector('#special')
// 创建实例
const io = new IntersectionObserver(
(entries) => {
// 是否进满足条件
if (entries[0].isIntersecting) {
const url = special.getAttribute('data-url')
// 满足条件的时候才赋值加载图片
special.src = url
// 取消观察
io.unobserve()
}
},
// option
// root目标元素的父元素
// rootMargin:距离100px的时候触发
// threshold: 50%的时候触发
{
root: div,
rootMargin: '100px',
threshold: [0.5]
}
)
// 开始观察
io.observe(special)

浙公网安备 33010602011771号