What is Intersection Observer

The Intersection Observer API provides Web developers with the ability to asynchronously query the position of elements relative to other elements or Windows. It is often used to track the visibility of an element in a window, such as the image below, which shows the visibility of a green square at the top of a scrolling page.

Prior to the creation of Intersection Observer, traditional location calculations relied on polling DOM states, which were densely executed in the main thread and caused page performance problems. Frequent calls to getBoundingClientRect() can also cause browser style recalculation and layout. If it is in an IFrame, we cannot access the element directly because of the same origin policy, and it is difficult to handle the element in an IFrame in the traditional way.

Intersection Observer the Intersection Observer is designed to easily handle elements’ visibility. Intersection Observer We use Intersection Observer to easily monitor elements entering and leaving visual Windows, and to preload and lazily load nodes. Intersection Observer is not a real-time computation based on pixel changes. Its feedback is delayed. This asynchronous approach reduces costly computation and continuous polling of DOM and style queries, and reduces CPU and GPU consumption compared to traditional methods.

Intersection Observer Usage

// Define the intersection monitor
var observer = new IntersectionObserver(changes= > {
  for (const change of changes) {
    console.log(change.time);               // The time of the change
    console.log(change.rootBounds);         // Information about the rectangular region of the root element
    console.log(change.boundingClientRect); // Information about the rectangular area of the target element
    console.log(change.intersectionRect);   // Information about the area where the target element intersects with the viewport (or root element)
    console.log(change.intersectionRatio);  // The ratio of the target element to the viewport (or root element)
    console.log(change.target);             // The object being observed}}, {});// Start observing a target element
observer.observe(target);

// Stop observing a target element
observer.unobserve(target);

// Close the monitor
observer.disconnect();
Copy the code

1. IntersectionObserver Callback

When the intersection between the target element and the root element changes, the monitor’s callback is triggered.

callback IntersectionObserverCallback = void (
    sequence<IntersectionObserverEntry> entries, 
    IntersectionObserver observer
);
Copy the code

The callback parameter, entries is a IntersectionObserverEntry array, the length of the array is our monitor target element number, another parameter is IntersectionObserver object.

2. IntersectionObserver Entry

IntersectionObserverEntry object provides the target element and intersecting elements for detailed information. It has the following attributes.

interface IntersectionObserverEntry {
  readonly attribute DOMHighResTimeStamp time;
  readonly attribute DOMRectReadOnly? rootBounds;
  readonly attribute DOMRectReadOnly boundingClientRect;
  readonly attribute DOMRectReadOnly intersectionRect;
  readonly attribute boolean isIntersecting;
  readonly attribute double intersectionRatio;
  readonly attribute Element target;
};
Copy the code

  1. Time: indicates the time when the intersection occurs, in milliseconds.
  2. RootBounds: Information about the rectangle area of the root element, or null if the root element is not set, as shown in blue.
  3. BoundingClientRect: Information about the rectangular region of the target element, the region in the figure with the black border.
  4. IntersectionRect: intersecting area of target element and viewport (or root element), intersecting area of blue square and pink square in the figure.
  5. IsIntersecting: whether the target element intersects the root element
  6. IntersectionRatio: intersecting ratio of target element and viewport (or root element).
  7. Target: The target element, the part of the diagram with the black border.

3. IntersectionObserver Option

IntersectionObserver Option is the second parameter of the IntersectionObserver constructor and is used to configure part of the monitor information.

dictionary IntersectionObserverInit {
  Element?  root = null;
  DOMString rootMargin = "0px";
  (double or sequence<double>) threshold = 0;
};
Copy the code
  1. Root: Sets the root node of the monitor. If the root node is not transmitted, it is the viewport by default.
  2. RootMargin: margin property similar to CSS. Use to shrink or expand rootBounds to affect the firing of the intersection.
  3. Threshold: The callback function is triggered when the threshold property determines the intersection ratio. The value can be 0 to 1 or an array of 0 to 1. As shown in the figure below, when we set threshold to [0, 0.25, 0.5, 0.75, 1] and the green squares are visible at 0%, 25%, 50%, 75% and 100%, the callback function will be triggered.

Intersection Observer Uses scenarios

1. Build custom preloaded or lazy loaded DOM and data.

For example, we can use Intersection Observer to lazily load images when they reach the user’s viewable area. Optimize the performance of large websites, give priority to rendering the view visible to the user, scroll according to the user page, load the view on demand.

2. Implement high performance scrolling lists.

Implement the list of pull up load, reduce the long list of sliding stuck.

3. Calculate the visibility of elements.

Optimize the effectiveness of advertising campaigns, and count ads only when they are visible to the user. To realize the user to remove the visual area of the player when the automatic pause, into the visual area and then play. Also can efficiently achieve parallax animation.

Intersection Observer compatibility

reference

  1. IntersectionObserver ‘s “Coming into View
  2. w3c Intersection Observer doc