0Pricing
HTML Academy · Lesson

Lazy Loading with IntersectionObserver

Defer image and content loading until they enter the viewport.

Beyond Native loading="lazy"

Native lazy loading covers <img> and <iframe>. For anything else — background images, video, expensive components, third-party widgets — IntersectionObserver is the right tool to defer work until the element is near the viewport.

The Pattern

Mark deferred elements with a data-src attribute holding the real source; render a tiny placeholder. Observe each one; on intersection, swap data-src to src (or otherwise activate the element) and unobserve so the callback never fires again.

<img class="lazy" data-src="/photo.jpg" alt="Photo" width="800" height="600">
<script>
const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      entry.target.src = entry.target.dataset.src;
      observer.unobserve(entry.target);
    }
  }
}, { rootMargin: "200px" });
document.querySelectorAll(".lazy").forEach((img) => observer.observe(img));
</script>

All lessons in this course

  1. IntersectionObserver API and Thresholds
  2. Lazy Loading with IntersectionObserver
  3. Infinite Scroll Implementation
  4. Scroll-Linked Animations Setup
← Back to HTML Academy