We're live-coding on Twitch! Join us!
Lazy Loading Images for Performance Using Intersection Observer

Lazy Loading Images for Performance Using Intersection Observer


]Images take up a higher percentage of the size of your website. Some of these images are below the fold which means they are not seen immediately the website visitor visits your website. They will need to scroll down before they can view the images. What if you could show only images viewed immediately then preload those below the fold? Yes you can. That’s what this post is about. Somewhere you must have seen a feature like this is on Medium.

I wrote an article on how to use the Intersection Observer API to implement infinite scroll in React. If we can implement infinite scroll, then we should also be able to load images progressively. Both fall under lazy-loading in the user experience mystery land. You should refer to the article introduction to understand how Intersection Observer works.

Considering Image Source

The example we’ll be considering in this post will contain 5 images or more but each of them will have this structure:




Each tag will have a data-src and a src attribute:

  1. data-src is the actual URL for the image (width: 500px) we want the reader to see.
  2. src contains very small resolution of the same image (width: 5px). This resolution will be stretched to fill up the space and give the visitor a blurred effect while the real image loads. The smaller image is 10 times smaller so if all conditions are normal, it would load faster (10 times).

The images are stored on a Cloudinary server which makes it easy to adjust the dimension of the images through the URL (h_300,w_500 or h_3,w_5).

The Observer

An observer is an instance of Intersection Observer. You create the instance and use this instance to observe a DOM element. You can observe when the element enters the viewport:

    const options = {
      rootMargin: '0px',
      threshold: 0.1

    const observer = new IntersectionObserver(handleIntersection, options);

The instance takes a handler and an options argument. The handler is the function called when a matched intersection occurs while the options argument defines the behavior of the observer. In this case, we want the handler to be called as soon as the image enters the viewport (threshold: 0.1).

You can use the observer to observe all images in the page:

    const images = document.querySelectorAll('img');

    images.forEach(img => {

Handling Intersection

We used a method for the handler but didn’t define it. That will scream an error as expected. Let’s create the handler above the instance:

    const handleIntersection = (entries, observer) => {
      entries.forEach(entry => {
        if(entry.intersectionRatio > 0) {

The method is called by the API with an entries array and an observer instance. The entries stores an instance of all the matched DOM elements (imgs in this case). If it’s matched, we call loadImage with the element.

loadImage fetches the image and then sets the image src appropriately:

    const loadImage = (image) => {
      const src = image.dataset.src;
      fetchImage(src).then(() => {
        image.src = src;

It does this by calling the fetchImage method with the data-src value. When the actual image is returned, it then sets the value of image.src.

fetchImage fetches the image and returns a promise:

    const fetchImage = (url) => {
      return new Promise((resolve, reject) => {
        const image = new Image();
        image.src = url;
        image.onload = resolve;
        image.onerror = reject;

Other Considerations

Considering smooth user experience, you can also add a fade in effect to the image when transitioning from blurry to crisp. This makes it more appealing to the eyes if the load time is perceived as being slower to the viewer.

Note that Intersection Observer is not widely supported in all browsers so you might consider using a polyfill or automatically loading the images once the page loads:

    if ('IntersectionObserver' in window) {
      // Observer code
      const observer = new IntersectionObserver(handleIntersection, options);
    } else {
      // IO is not supported.
      // Just load all the images
       Array.from(images).forEach(image => loadImage(image));


We will keep striving to give our users better experience in 2018 and ahead. Performance is what we should be worried about because competitors are awake and your users will swing away as soon as you waste their time or they have a bad experience. With progressive images, you are able to cut down on a huge amount of time wasted by the users resources to download your content.

Like this article? Follow @codebeast on Twitter