Quantcast
Channel: DigitalOcean Community Tutorials
Viewing all articles
Browse latest Browse all 136

How To Lazy-Load Images with Intersection Observer

$
0
0

Introduction

Images take up a high percentage of the size of your website. Some of these images are below the fold, which means they are not seen immediately by the website visitor. They will need to scroll down before they can view the images. Imagine if you could show only images viewed immediately, then pre-load those below the fold. This tutorial will show you how that’s done.

See the previous tutorial 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 the Image Source

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

<img 
     src="http://res.cloudinary.com/example/image/upload/c_scale,h_3,w_5/0/example.jpg" 
     data-src="http://res.cloudinary.com/example/image/upload/c_scale,h_300,w_500/0/example.jpg"
>

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 will 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).

Step 1 — Using 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 => {
      observer.observe(img);
    })

Step 2 — Handling Intersection

In the previous step, you used a method for the handler but didn’t define it. That will throw an error. Let’s create the handler above the instance:

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

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, or img elements in this case. If it’s matched, the code calls 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;
      });
    }

Step 3 — Enhancing the User Experience

Considering a 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 IntersectionObserver 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));
    }

Conclusion

In this tutorial, you configured lazy-loading for images on your website. This will enhance the performance of your site while also providing the user with a better experience.


Viewing all articles
Browse latest Browse all 136

Trending Articles