Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How does the Intersection Observer API work with lazy loading
    Intersection Observer API lazy loading web performance image lazy loading JavaScript web development


How does the Intersection Observer API work with lazy loading


The Intersection Observer API is used to implement lazy loading in a web page by asynchronously detecting when an element enters the viewport and then performing an action, such as loading an image, afterward. Here's a step-by-step explanation of how it works:

Step 1: HTML Structure

Create the HTML structure for the elements you want to lazy load. For example, if you want to lazy load images, you can use the following structure:

html
<img data-src="image_url.jpg" src="placeholder_image.jpg" alt="image-to-lazy-load" class="lazy-image" />

Step 2: JavaScript Implementation

1. Find Elements to Observe: Identify the elements that need to be lazy loaded and store them in a variable. For example, if you want to lazy load images, you can use `document.querySelectorAll('.lazy-image')`.

2. Create an IntersectionObserver Instance: Create an instance of the IntersectionObserver API by calling its constructor and passing a callback function (`lazyLoad`) and optional options.

3. Callback Function: Define the callback function (`lazyLoad`) that will be executed when the target element intersects with the viewport. This function should handle the lazy loading of the image by setting the `src` attribute to the desired image URL and removing the `data-src` attribute.

4. Observe Elements: Loop through the elements to be lazy loaded and pass each element to the `observe` method of the IntersectionObserver instance.

Example Code

Here's an example of how you can implement lazy loading using the Intersection Observer API:

javascript
// Find all elements with the 'lazy-image' class and 'data-src' attribute
const lazyImages = document.querySelectorAll('.lazy-image');

// Callback function for the IntersectionObserver
const lazyLoad = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      img.removeAttribute('data-src');
      observer.unobserve(img);
    }
  });
};

// Create an IntersectionObserver instance
const observer = new IntersectionObserver(lazyLoad, {
  rootMargin: '100px', // Adjust this value as needed
});

// Observe each lazy image
lazyImages.forEach(image => {
  observer.observe(image);
});

How it Works

1. Initialization: The IntersectionObserver API is initialized with a callback function (`lazyLoad`) and optional options.

2. Observation: Each element to be lazy loaded is passed to the `observe` method of the IntersectionObserver instance.

3. Intersection Detection: The IntersectionObserver API asynchronously detects when the target element intersects with the viewport.

4. Action: When the target element intersects with the viewport, the callback function (`lazyLoad`) is executed. This function sets the `src` attribute of the image to the desired image URL and removes the `data-src` attribute.

5. Unobservation: After the image is loaded, the `unobserve` method is called to stop observing the element.

By using the Intersection Observer API, you can implement lazy loading in your web page, which can significantly improve the initial page load time and overall performance.

Citations:
[1] https://www.audreyhal.com/blog/lazy-loading-images-with-intersection-observer-api
[2] https://dev.to/samuelorobosa/lazy-loading-with-intersection-observer-api-4oi4
[3] https://www.linkedin.com/pulse/how-achieve-lazy-loading-using-intersection-observer-api-nath
[4] https://stackoverflow.com/questions/70723000/how-to-lazy-load-images-using-intersection-observer
[5] https://miletadulovic.me/blog/lazy-loading-images-with-intersection-observer-in-react