Web APIs #3 — Intersection Observer

Lazy load images, infinite scroll, and track ad visibility — all without scroll event handlers. Understanding thresholds, rootMargin, and the observer callback.

10 min read
JavaScript
Web API
Observer
Performance

TABLE OF CONTENTS
Web APIs #3 — Intersection Observer

Scroll event handlers are expensive — they fire at ~60Hz and force layout calculations. IntersectionObserver is the modern replacement: it tells you when an element enters or leaves the viewport without any scroll handlers. This article covers lazy loading, infinite scroll, and ad viewability tracking.


1. Basic Observer — Detect When an Element Becomes Visible

Loading editor...


2. Options — threshold, rootMargin, root

Loading editor...


3. Lazy Loading Images Pattern

Loading editor...


4. Infinite Scroll Pattern

Loading editor...


5. Sticky Header Shadow on Scroll

Loading editor...


6. Intersection Observer vs Scroll Events

Loading editor...


Key Takeaways

  • IntersectionObserver fires asynchronously — no reflow, no scroll handler overhead.
  • rootMargin lets you trigger before the element is visible (prefetch, lazy load).
  • threshold controls what percentage of visibility triggers the callback.
  • Always unobserve elements when done (e.g., after lazy-loading an image).
  • intersectionRatio tells you how much of the element is visible (0–1).
  • IO replaces: scroll position checks, getBoundingClientRect() calls, scroll-spy, ad viewability, and lazy loading.

Next: DOM Events #1 — Event Delegation & Bubbling — handle hundreds of elements with a single listener.


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI