> For the complete documentation index, see [llms.txt](https://1425816423.gitbook.io/my-knowledge-base/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://1425816423.gitbook.io/my-knowledge-base/qian-duan-an-quan-yu-xing-neng-you-hua/qian-duan-xing-neng-you-hua/tu-pian-lan-jia-zai.md).

# 图片懒加载

tags: 前端性能 Created time: July 19, 2022 5:58 PM emoji: 🖼️

## getBoundingClientRect

getBoundingClientRect方法可以获取元素的大小和距离视口左/上方的距离，可以通过以下算式判断元素是否出现在视口中。

```jsx
img.getBoundingClientRect().top - clientHeight < 0
```

首先将图片url存放到`data-src`属性中，另外需要给图片设置`width`、`height`属性来占位，然后为页面滚动事件添加事件处理程序，滚动时判断每个图片元素是否出现在视口中。

另外为了减少性能消耗，可以利用节流来减少滚动事件处理程序的执行频率。

完整代码如下：

```jsx
// 节流
function fn(cb,delay=300){
    let timer
    return function(...args){
        if(!timer){
            cb.call(null,...args)
            timer = setTimeout(()=>{
                timer = null
            },delay)
        }
    }
}

function imgLoad(){
    const clientHeight = document.documentElement.clientHeight
    const imgs = document.querySelectorAll("img[data-src]")
    console.log(1, imgs[imgs.length-1].getBoundingClientRect().top -  clientHeight );
    for(img of imgs){
        if(img.getBoundingClientRect().top - clientHeight < 0){
            img.setAttribute('src', img.getAttribute('data-src'))
            img.removeAttribute('data-src')  // 移除属性，避免之后又被获取
        }
    }
}

const handleImgLoad = fn(imgLoad)
document.addEventListener('scroll',handleImgLoad)
```

## InterSectionObserver

Web为开发者提供了 IntersectionObserver 接口，它可以异步监听目标元素与其祖先或视窗的交叉状态，注意这个接口是异步的，它不随着目标元素的滚动同步触发，所以它并不会影响页面的滚动性能。

IntersectionObserver 构造函数接收两个参数，回调函数以及配置项。

* root：所监听对象的具体祖先元素，默认是 viewport ；
* rootMargin：计算交叉状态时，将 margin 附加到祖先元素上，从而有效的扩大或者缩小祖先元素判定区域；
* threshold：设置一系列的阈值，当交叉状态达到阈值时，会触发回调函数。

IntersectionObserver 实例执行回调函数时，会传递一个包含 IntersectionObserverEntry 对象的数组，该对象一共有七大属性：

* time：返回一个记录从 IntersectionObserver 的时间原点到交叉被触发的时间的时间戳；
* target：目标元素；
* rootBounds：祖先元素的矩形区域信息；
* boundingClientRect：目标元素的矩形区域信息，与前面提到的 Element.getBoundingClientRect() 方法效果一致；
* intersectionRect：祖先元素与目标元素相交区域信息；
* intersectionRatio：返回intersectionRect 与 boundingClientRect 的比例值；
* isIntersecting：返回一个布尔值，如果目标元素与交叉区域观察者对象 (intersection observer) 的根相交，则返回 `true`.如果返回 `true`, 则 `IntersectionObserverEntry` 描述了变换到交叉时的状态; 如果返回 `false`, 那么可以由此判断，变换是从交叉状态到非交叉状态。

完整代码

```jsx
function observe() {
  const observer = new IntersectionObserver(
    (changes) => {
      console.log(changes);
      changes.forEach(function (change) {
        if (change.isIntersecting) {
          const img = change.target;
          img.setAttribute("src", img.getAttribute("data-src"));
          img.removeAttribute('data-src')
          observer.unobserve(img);
        }
      });
    },
    {
      root: null,
      rootMargin: "0px",
    }
  );

  const imgs = document.querySelectorAll("img[data-src]");
  for (img of imgs) {
    observer.observe(img);
  }
}

observe();
```
