讲述一次图片懒加载性能优化
# 场景

- 上述截图是实际业务中查询的数据,每个大屏背后都有一张缩略图
 - 也就是说除了要拿到数据开始渲染外,还要每个 block 拿到 url,请求自己缩略图
 - 其实每页最多能显示 15 block。他的分页动作是:下滑分页
 - 当开始下滑的过程中 还有加载更多的数据
 - 上述场景会造成,在 http1 协议中 会出现大量的图片请求
 
# 优化
- 所以在这种场景下,图片懒加载的方式非常有必要的。我方解决方式是使用 API
 IntersectionObserver来实现图片请求异步的方式- 其实也可以通过监听滑动,来计算每个图片是否在可视区,也是可以的实现的
 
# 兼容性

- 通过上述截图可以看到,其实兼容性还是很不错的
 
# 实现代码
  const intersectionObserver = new IntersectionObserver(
    (entries) => {
      // 解构 image原数据 以及激活状态
      const { target, intersectionRatio } = entries[0]
      const el = target as HTMLImageElement
      // 如果已经出现在可见区域  直接进行请求
      if (intersectionRatio > 0.2) {
        const { dataset } = el
        // 如果传递的path 没有值的话 直接取消监听
        if (!dataset.path) {
          intersectionObserver.unobserve(target)
          return
        }
        el.src = `${import.meta.env.VITE_HTTP_PREFIX}${dataset.path as string}`
        intersectionObserver.unobserve(target)
      }
    },
    {
      threshold: [0.25, 0.75]
    }
  )
  // 添加监听的dom
  intersectionObserver.observe(thumbnailRef.value!)
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
通过上述代码可以看到,其实原理还是很简单的。其实最重要的是 懂的如何去优化