Detailed explanation of IntersectionObserver API

In the past, it was not easy to detect whether an element was visible or whether two elements intersected. For example, when implementing functions such as lazy loading of images and infinite scrolling of content, it was necessary to write a lot of logic calculations through ​getBoundingClientRect()​ or rely on poor performance methods such as scroll event monitoring.

Now, relying on IntersectionObserver , we can realize the above functions very conveniently and efficiently.

1. APIs

// 创建实例
const observer = new IntersectionObserver(callback, option);

// 开始观察element1
observer.observe(element1);

// 开始观察element2
observer.observe(element2);

// 停止观察
observer.unobserve(element);

// 关闭观察器
observer.disconnect();

IntersectionObserverIt is a constructor provided natively by the browser and accepts two parameters: callbackthe callback function when the visibility changes, optionand the configuration object (this parameter is optional).

The return value of the constructor is an observer instance. The instance observemethod can specify which DOM node to observe. If you need to observe multiple DOM nodes, you can add the observe method multiple times.

Two, the callback parameter

The callback function is invoked when:

  • When Observer listens to the target element for the first time
  • Executed whenever the target element intersects with the device window or other specified elements

  

callbackThe function parameter ( entries) is an array, each member is an IntersectionObserverEntry object. For example, if the visibility of two observed objects changes at the same time, entriesthe array will have two members.

The meaning of each IntersectionObserverEntry object property is as follows:

  • boundingClientRect: information about the rectangular area of ​​the target element
  • intersectionRatio: The visible ratio of the target element, that is, the ratio of intersectionRectthe target boundingClientRectelement, when it is fully visible 1, it is less than or equal to when it is completely invisible0
  • intersectionRect: Information about the intersection area between the target element and the viewport (or root element)
  • rootBounds: The information of the rectangular area of ​​the root element, getBoundingClientRect()the return value of the method, if there is no root element (that is, scrolling directly relative to the viewport), it will be returnednull
  • isIntersecting : Whether the target element intersects with the viewport (or the root element)
  • isVisible : The relevant information has not been checked, and it will not change after testing
  • target: The observed target element is a DOM node object
  • time: The time when the visibility changed, which is a high-precision timestamp in milliseconds

3. Option object

IntersectionObserverThe second parameter of the constructor is a configuration object. It can set the following properties.

  • rootSpecifies the root element for checking the visibility of the target. Must be a parent element of the target element. If not specified or is null, defaults to the browser window.
  • rootMargin: The outer margin of the root element, similar to the margin property in CSS.
  • threshold: The intersection ratio between the target element and the root element, which can be a single number or an array of numbers. For example, it [0, 0.25, 0.5, 0.75, 1]means that the callback function will be triggered when the target element is 0%, 25%, 50%, 75%, or 100% visible.

 4. Notes

  • The IntersectionObserver API is asynchronous and does not trigger synchronously with the scrolling of the target element.
  • The registered callback function will be executed in the main thread, so the execution speed of this function should be as fast as possible. If there are some time-consuming operations that need to be performed, it is recommended to use  the Window.requestIdleCallback()  method.

5. Example: infinite scrolling

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>IntersectionObserver</title>
</head>
<body style="font-size: 24px;text-align: center">
<div id="container"></div>
<div id="loadMore">加载中...</div>
</body>
<script>
  const container = document.querySelector('#container');
  const loadMore = document.querySelector('#loadMore');
  let index = 0;

  const loadItems = (count) => {
    [...Array(count).keys()].forEach((key) => {
      const p = document.createElement('P');
      p.innerHTML = `${key + index}`;
      container.appendChild(p)
    })
    index += count;
  }

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(({ isIntersecting }) => {
      if (isIntersecting) {
        loadItems(20);
      }
    })
  });

  observer.observe(loadMore)
</script>
</html>

The implementation of infinite scroll (infinite scroll) is also very simple. By observing whether the #loadMore element intersects with the browser view, if it intersects, it means that the list has been loaded, and continue to add more elements.

 

reference:

Intersection Observer API - Web API interface reference | MDN

IntersectionObserver API tutorial - Ruan Yifeng's weblog

Guess you like

Origin blog.csdn.net/qq_38629292/article/details/127200527