JAVASCRIPT

Lazy Load Images with IntersectionObserver

Optimize page load times by lazy loading images only when they enter the viewport using the efficient IntersectionObserver API for better performance.

document.addEventListener('DOMContentLoaded', () => {
  const lazyImages = document.querySelectorAll('img[data-src]');
  const observerOptions = {
    root: null, // viewport
    rootMargin: '0px',
    threshold: 0.1 // 10% visible
  };

  const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        if (img.dataset.srcset) {
          img.srcset = img.dataset.srcset;
        }
        img.removeAttribute('data-src');
        img.removeAttribute('data-srcset');
        observer.unobserve(img); // Stop observing once loaded
      }
    });
  }, observerOptions);

  lazyImages.forEach(img => {
    imageObserver.observe(img);
  });
});
How it works: This snippet demonstrates how to implement lazy loading for images using the IntersectionObserver API. Images are initially given `data-src` and `data-srcset` attributes instead of `src` and `srcset`. The observer watches for these images to enter the viewport. Once an image is sufficiently visible, its `data-src` and `data-srcset` values are transferred to `src` and `srcset` respectively, loading the image. This technique improves page performance by deferring image loading until necessary.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs