Skip to content
JavaScript

Image Lazy Loading

Implement image lazy loading with IntersectionObserver.

By EZ4Code Team
imagelazy-loadIntersectionObserver

Code

function lazyLoad(selector = "img[data-src]") {
  const observer = new IntersectionObserver((entries, obs) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;
        img.removeAttribute("data-src");
        obs.unobserve(img);
      }
    });
  });
  document.querySelectorAll(selector).forEach(img => observer.observe(img));
}

Explanation

Monitors elements entering the viewport via IntersectionObserver for on-demand loading.

More JavaScript Snippets