使用IntersectionObserver 实现懒加载 && 记录一个懒加载失效的原因

先说说我实现懒加载失效的一个原因:

是图片没有写高度

猜想是没有给图片高度,所以底层没法进行计算 容器是否出现在视图中

 

IntersectionObservers作用

提供了一种异步观察目标元素与其祖先元素或顶级文档视窗 (viewport) 交叉状态的方法,观察目标元素是否出现在视图窗口

 

实现一个IntersectionObserver

// 配置参数请看下面
// root:视图根节点,不填默认为浏览器窗口
// rootMargin:缩小或扩大根元素的区域,默认值为"0px 0px 0px 0px",只能用px或百分比
// threshold:可以给0 - 1 之间的数  0 元素刚进入窗口  1 完全进入窗口
const config = {
    root: null,
    rootMargin: '0px',
    threshold: 0
}
const io = new IntersectionObserver(
  callback,
  config
)

 

IntersectionObserver 提供的api

  • 开始监听一个目标元素
io.observe(element)
  • 停止监听特定目标元素
io.unobserve(element)
  • 使IntersectionObserver对象停止监听工作,停止观察服务
io.disconnect()

 

懒加载代码示例

html

 <img src="" data-src="https://img1.baidu.com/it/u=3498480268,360056650&fm=253&fmt=auto&app=138&f=PNG?w=662&h=500" alt="">

js

const imgs = Array.from(document.querySelectorAll('img[data-src]'))
const config = {
    rootMargin: '0px',
    threshold: 0,
}
const io = new IntersectionObserver((entries, self) => {
    entries.forEach((entry) => {
        if (entry.isIntersecting) {
            let img = entry.target
            let src = img.dataset.src
            if (src) {
                img.src = src
                img.removeAttribute('data-src')
            }
            // 解除观察
            self.unobserve(entry.target)
        }
    })
}, config)

imgs.forEach((image) => {
    io.observe(image)
})

 

posted @ 2022-08-29 13:34  时光凉忆  阅读(136)  评论(0编辑  收藏  举报