Lazy load images using IntersectionObserver

Motivation

Loading images on the web has always been a hot topic. If a user doesn’t see all your images, it doesn’t make sense to send down the wire all those extra bytes. All the techniques used to lazy load images in the past have used a combination of the browser provided APIs like getBoundingClientReact together with event listeners on each image to get the position of the element with respect to the viewport.

The problem with these approaches is the computations involved in the API is heavy and often results in users experiencing scroll janks navigating the site. With IntersectionObserver, all this would hopefully go away!

Solution

IntersectionObserver is an API baked right into your browser to help you combat the problem above.

Code

Check out the following Codepen for a demo on Intersection observer to lazy load images on a site:

The IntersectionObserver API accepts 2 arguments, a callback function and an options object. Checkout the MDN link to see the values for each of these options. Below is a brief one liner for what each options does.

root - The parent element with respect to which the intersection will be calculated. Defaults to null which means, the viewport.

rootMargin - Values specified here will add margin to the root element (specified by root) on all 4 sides.

threshold - Specifies what percentage of the target element (the element being observed) crosses the intersection for the callback to be fired.

Future possibilities

Instead of having an event listener on each and every image, we could have implemented this by having a placeholder ‘div’ in between a set of say, 10 images to load 10 images at once. We could then observe this placeholder instead to minimize the observers on our page and load images (in sets of 10) more effectively.

This would be great for a shopping site where you have a infinite scroll for images.

For those interested to explore more, here is a great article by Surma and Robert Flack on optimizing infinite scrolling:

https://developers.google.com/web/updates/2016/07/infinite-scroller

Conclusion

Intersection Observers are great and here to stay. You could feature detect the availability and go through loading all the images or lazy loading for your users. Check the following link for the available browser support.

https://caniuse.com/#search=intersectionobserver

Helpful links: Intersection Observer API The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element…developer.mozilla.org