Lazy Loading with IntersectionObserver

Load content when it enters the viewport.

Code

JavaScript
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src || img.src;
      observer.unobserve(img);
    }
  });
}, { rootMargin: "50px" });

document.querySelectorAll("img[data-src]").forEach((el) => observer.observe(el));

Line-by-line explanation

Expected output

Images load when scrolled into view

Related snippets