Lazy-load images with IntersectionObserver

Load an image only when it is close to the screen. (For simple cases loading="lazy" is enough.)

JavaScript · Lazy-load images with IntersectionObserverIntermediate
const io = new IntersectionObserver((entries, observer) => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;
    const img = entry.target;
    img.src = img.dataset.src;
    observer.unobserve(img);
  }
}, { rootMargin: '200px' });

document.querySelectorAll('img[data-src]').forEach((img) => io.observe(img));
intersectionobserverlazyimagesperformance