We're going to learn about the Intersection Observer API—a powerful way to lazy load elements in our applications.

In this article, we’re going to learn more about the Intersection Observer API, a new and powerful API that modern browsers now support that helps us to lazy load images and other elements in our web pages. We can use this API to understand the visibility of elements and implement pre-loading and deferred loading content of our DOM.

As the web has been evolving throughout the years, browsers are getting more and more support for a lot of new features and APIs, but something that is still a pain to developers from time to time is rendering content on DOM. When we’re starting a new application, creating components, thinking in our HTML structure, stylizing our CSS files, we’re already thinking about our rendering process, how our page layout is going to look, and some important parts that we must watch carefully to get a nice rendering on our application.



That makes a lot of difference in the application, how we’re going to create our elements, how we’re going to organize our CSS, what libraries and frameworks we’re going to use, etc. That’s why rendering is still a hot topic for developers.

One of the reasons that the React library, created by Facebook back in 2011, got so big and popular in the web development community is because this library works with something called virtual DOM. Basically, it’s a virtual representation of your DOM, that you can manipulate and update as you want. Then after all the updates, the virtual DOM will look at the specific changes that need to be made on the original DOM, and apply these changes in a nice, optimized way, so you’ll not have to update the whole page when the only changes were in a single element. That’s one of the biggest advantages of React in the face of the other libraries and frameworks nowadays. Rendering content on the DOM is hard work and an expensive task, but React makes it better and faster, without any kind of problem.

Some libraries or APIs can improve the rendering of our elements in our applications. That’s why we’re going to learn more about the Intersection Observer API and see how this new API can help us. First, let’s understand a little bit more about lazy loading, then we’re going to dive in and see how the Intersection Observer API works.

How Does Lazy Loading Work?

Lazy loading is a technique for rendering content on the web. Instead of rendering the entire page in one go and leaving the user with a heavier experience, the concept of lazy loading consists of loading only the required parts and delaying the rest until they are needed by the user.

An example of lazy loading that you must have heard of and may have used in your applications is the infinite scroll. The infinite scrolls work like this: the user enters the website, loads the initial content page, and, only when the user scrolls to the end, it loads more content. This way, there’s no need to load everything at once and have a huge and heavy application.

So, if lazy loading is the technique of rendering only the content that the user is going to need, what’s the inverse term? Some people might have heard of lazy loading before but don’t know exactly what’s the opposite. The opposite of lazy loading is called eager loading—when your user enters your website and it renders all the content right away.

Did you know that the web now has a new loading attribute, so we can lazy load images natively? To use it, all you need to do is pass a loading=lazy to your img or iframe element.

By using this technique, we have a lot of advantages: Loading resources as needed reduces the time consumption and memory usage if only one part of the page is rendered, and that means the time to load the page is reduced. It also helps with not rendering unnecessary code, which optimizes a lot your applications, especially for those who’re using in some slow network devices. But it also has some disadvantages like: It can affect your website’s ranking on search engines, and it also takes some time to implement it the right way, using the right libraries or APIs for the job.

Intersection Observer API

JavaScript has been evolving so quickly throughout the years that we're getting new web APIs almost every year, and the benefit of these new web APIs is to create better and more awesome applications and web pages.

The Intersection Observer is an API that we can use to keep track of the visibility and position of DOM elements. The game changer here is that it's delivered asynchronously, making it really useful for understanding the visibility of elements, so we can implement the pre-loading and deferred loading of our DOM content.

Image by Arnelle Balane

If we go back to the web some years ago, we didn't have an API or something similar to calculate and keep track of the position of an element. Most of the time, we ended up with some crazy and huge functions, creating expensive methods, causing us more problems than solutions. With this Intersection Observer API, we can create really nice things, many of which are used widely nowadays, like:

Infinite scrolls — By using this API, it has never been easier to create infinite scrolls such as tables, lists, grids, etc.

— By using this API, it has never been easier to create infinite scrolls such as tables, lists, grids, etc. Images — There's no need to render all the images of your web page at once; you can lazy load the images and only render the images that are needed for the user at the moment.

— There's no need to render all the images of your web page at once; you can lazy load the images and only render the images that are needed for the user at the moment. Monitor elements — You can keep track of your elements in your page; you can monitor elements and see if they're being rendered to the user A real case for this is for advertisements on the page, so you can report when an ad was displayed.

This is how we can start to use the Intersection Observer API:

let myFirstObserver = new IntersectionObserver(callback, options);

First, we call the IntersectionObserver constructor and this IntersectionObserver receives two parameters. First is the callback function, which is called when an element intersects our device viewport or a specific element; the options parameter is an object, and this object controls the circumstances of how your callback is invoked. The options object has the following fields:

root — The parent element that’s been used as the viewport of the target element.

rootMargin — The margin around the root element, it receives values similar to CSS margin properties. These values can grow or shrink each side of the root element’s box before computing an intersection.

threshold — It can be a number or an array of numbers, and it indicates what percentage of the target’s visibility the observer’s callback function should be invoked.

Image by Arnelle Balane

So, let's start to use the Intersection Observer API. We're going first to log to the console every element.

let options = { root: document.querySelector('.scroll-list'), rootMargin: '5px', threshold: 0.5 }; let myFirstObserver = new IntersectionObserver(elements => { elements.forEach(element => console.log("element", element)); }, options);

Now, to start to "observe" an element, all we need to do is to get the specific target that we want, and then call the observer with the observe function, passing the target element, like this:

let myDivTarget = document.querySelector('.header'); observer.observe(myDivTarget);

You should remember that all elements considered by the Intersection Observer API are rectangles; elements which are irregularly shaped are considered as occupying the smallest rectangle that encloses all of the element’s parts.

But what about the support for the Intersection Observer API nowadays? Are browsers really supporting this new API? The answer is: Unless you're going to develop for IE or some really old browser, you can use it without worrying, since it's supported on the latest version of the most-used browsers, such as Chrome, Edge, Firefox and Opera.

If you’re going to deal with a lot of data, for example, a table with a lot of information, the Intersection Observer API can be extremely helpful in creating a table that only renders the content that’s needed by the user, and no extra content.

One of the advantages of this API is that you don't have to use a library for this kind of job anymore. The majority of browsers are providing a lot of support for some of the newest and awesome APIs, and this has been improving the experience for users in general, allowing developers to use some native browser APIs and reducing their final code bundle.

Conclusion

In this article, we learned about the Intersection Observer API and how this API can help us to make better pages by lazy-loading them, keeping track of the position of our DOM elements, etc. Browsers are providing more and more native support for web APIs, and this API is particularly helpful for reducing the time of rendering, benefiting users with slow network connections, reducing the bundle of your web page, and only rendering the content that your user needs.



Don’t stop your learning here—keep learning and discovering more about this API, create some mind-blowing web pages and feel how this API can benefit you on a daily basis.