Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Using the Javascript Intersection Observer API to improve performance

The Intersection Observer API will watch for when an element enters or exits the view.

Till recently this was managed by a combination of the scroll event and the Element.getBoundingClientRect() method. But the Intersection Observer API gives us a faster alternative.

So, let's say we have a #my-special-div element. To watch for it entering or exiting the viewport, we will write something like:

const observer = new IntersectionObserver( (entries) => {
    entries.forEach((entry)=> {
        console.log("The red div is on screen = " + entry.isIntersecting)
    });
});

const myElement = document.querySelector('#my-special-div');
observer.observe(myElement);

Below is the full working codepen:

See the Pen
Intersection Observer
by JS Craft (@js-craft)
on CodePen.

Seen this recent article, where the guys from Github were explaining how they used the Intersection Observer API to:

  1. improve the performance by listening for when a video enters the view and lazy load it. For images, we can do this in a native way with the loading attribute.
  2. and also they used the Intersection Observer to add smooth entering animations. Before Intersection Observer they were using the scroll and resize events that are not as good performance-wise.

The support for it is great being now available in all browsers.