CodePark/ questions / Browser APIs
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Browser APIs

What is IntersectionObserver, and why is it better than a scroll listener for lazy loading or infinite scroll?

const observer = new IntersectionObserver((entries) => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;
    loadMore();
    observer.unobserve(entry.target);
  }
}, { rootMargin: "200px" });

observer.observe(document.querySelector("#sentinel"));

IntersectionObserver calls you back when an element starts or stops overlapping the viewport, or another root element. It fires at a threshold you choose. The callback is asynchronous, so it doesn't block the page.

Why it beats a scroll listener:

  • A scroll listener fires very often, on the main thread.
  • Checking visibility with getBoundingClientRect forces layout each time.
  • You must throttle the listener yourself.

With IntersectionObserver, the browser computes intersections efficiently. It only notifies you when something changes.

The example watches a sentinel: an empty marker element placed at the end of a list. When the sentinel comes into view, the code loads more items. It uses rootMargin to start loading 200px before the sentinel is visible.

Common uses:

  • lazy loading images or components
  • infinite scroll
  • analytics for impressions (counting which items users actually saw)
  • pausing videos or animations that are offscreen

Call unobserve or disconnect when you're done watching.

  • IntersectionObserver calls you back asynchronously when visibility crosses a threshold.
  • It needs no scroll handlers and causes no forced layout.
  • rootMargin triggers the callback early, and threshold sets the visible ratio.
  • It is used for lazy loading, infinite scroll and impression tracking.
  • Call unobserve or disconnect when you are done.