DEV Community

Cover image for Working with the Intersection Observer API for Lazy Loading
Patoliya Infotech
Patoliya Infotech

Posted on

Working with the Intersection Observer API for Lazy Loading

When it comes to creating high-performance web apps, efficient resource loading is crucial. The Intersection Observer API is a powerful but often ignored feature provided by current browsers. It makes it easier to perform tasks such as lazy loading pictures, infinite scrolling, and triggering animations on scroll without having to write expensive scroll event listeners.

In this post, we will look at how the Intersection Observer API works, why it is useful, and how to utilize it for lazy loading in a clean and efficient manner.

Why Lazy Loading Matters

Lazy loading is the practice of delaying the loading of non-critical resources (such as photos, videos, or iframes) until they are required—typically when they show in the viewport.

Benefits include:

  • Performance Boost – Faster page load times.
  • Reduced Bandwidth – Users don’t download assets they never see.
  • Better UX – Improves perceived performance on mobile devices.

Traditionally, developers used'scroll' event listeners to enable lazy loading, but this method can get messy and compromise performance. This is where the Intersection Observer API excels.

What is the Intersection Observer API?

The Intersection Observer API enables you to asynchronously monitor changes in the intersection (visible) of a target element with a parent element or the viewport.

In simpler terms:

  • You tell the browser: "Hey, let me know when this element becomes visible (or invisible) on the screen."
  • The browser handles the rest in a performant way.

Basic Syntax

const observer = new IntersectionObserver(callback, options);
observer.observe(targetElement);
Enter fullscreen mode Exit fullscreen mode
  • callback → Runs whenever the visibility of the element changes.
  • options → Defines root, root margin, and threshold.
  • observe → Tells the observer which element to watch.

Curious why PHP remains a go-to for e-commerce in 2025? Discover how it powers modern online stores and why it could be the perfect choice for your business!

Using Intersection Observer for Lazy Loading

Let’s build a lazy-loading image system using this API.

Step 1: HTML Markup

<img data-src="image1.jpg" alt="Lazy Loaded Image" class="lazy-image" />
<img data-src="image2.jpg" alt="Lazy Loaded Image" class="lazy-image" />
<img data-src="image3.jpg" alt="Lazy Loaded Image" class="lazy-image" />
Enter fullscreen mode Exit fullscreen mode

Notice we’re using data-src instead of src. The actual src will be set once the image enters the viewport.

Step 2: JavaScript Logic

const images = document.querySelectorAll(".lazy-image");

const lazyLoad = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.getAttribute("data-src");
      img.removeAttribute("data-src");
      observer.unobserve(img);
    }
  });
};

const observer = new IntersectionObserver(lazyLoad, {
  root: null, // viewport
  rootMargin: "0px 0px 50px 0px", // preload before visible
  threshold: 0.1 // trigger when 10% visible
});

images.forEach(img => observer.observe(img));
Enter fullscreen mode Exit fullscreen mode

Why This Approach Works Well

  • No manual scroll handling – Browser handles performance.
  • One observer for many elements – Efficient resource use.
  • Fine-grained control – Load elements just in time.

Other Use Cases Beyond Lazy Loading

The Intersection Observer API isn’t just for lazy loading. You can also use it for:

  • Infinite scrolling – Load new content as users scroll down.
  • Scroll-triggered animations – Animate elements when they appear.
  • Ad/Analytics tracking – Detect when an element enters the viewport.

Quick Tips

  • Use rootMargin to preload content slightly before it enters view.
  • Set a low threshold (like 0.1) for early triggers.
  • Always unobserve elements once you’re done to avoid memory leaks.

Final Thoughts

The Intersection Observer API is one of those things that may greatly simplify your code while also enhancing performance. Lazy loading offers a cleaner, more efficient alternative to scroll-based reasoning.

Mastering this API is essential for developing modern, performance-driven online apps.

Need expert PHP developers? Let’s build scalable and maintainable applications together! Contact Us Today

Top comments (0)