Intersection Observer - A Better Way to Know What’s on Your Screen

Nora LC
3 min readJun 24, 2021

About Intersection API Usage

Source

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport - from MDN. In this blog post, I’m going to show how it could help us improve the performance of websites operations with the DOM.

Let’s start by taking a look at this HTML code:

<html lang="en">

<!-- <head> -->

</script>
</head>
<body>
<p>exampleexampleexample</p>
<ul>
<li> example </li>
<li> example </li>
</ul>
<h1>Test</h1>
<ul>
<li> example </li>
<li> example </li>
</ul>
</body>

Let’s say we needed to keep track of the h1element visibility. Meaning we want to know when our h1element is in the visible section of the browser.

A naive approach to this would be to manually check if the DOM element is on the screen every time there is a scroll event. In practice, this is quite an expensive operation. In order to do so, you have to first query the page for all elements you are interested in. Then you have to add a scroll event listener which gets triggered every time the user scrolls. For every scroll event, you then have to manually calculate if each of the elements is on the screen.

The code would look like something like this.

let h1Element = document.querySelector('h1');
const isInView = (elm, {top, height} =
elm.getBoundingClientRect()) => top <= innerHeight && top + height >= 0;
document.addEventListener('scroll', (e) => {
if(isInView(h1Element)) {
console.log('element is in view');
} else {
console.log('element is not in view');
}
});

This works but is incredibly non-optimal. We are running code when we don’t have to and always needing to run some math.

The much better approach for this is using Intersection Observers. The Intersection Observer API comes as native functional to browsers (as of XXX release) and allows us to asynchronously observe changes that happen to the viewport. It allows us to monitor which elements have come onto or moved off of the visible portion of the screen. When an element enters or exits the screen, the Intersection Observer is triggered with a list of entries that tells us what elements have entered or exited along with a bunch of other information about that event.

Take a look at how this problem can be solved using an Intersection Observer:

Et voila!
Proof it’s working! 👊

Conclusion

We needed to run far less code in order to use the intersection observer than any other traditional approach. Keep in mind that not some old browsers don’t support it. Although you can use Polyfills to get functionality across browsers.

--

--