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
IntersectionObserverfires asynchronously — no reflow, no scroll handler overhead.rootMarginlets you trigger before the element is visible (prefetch, lazy load).thresholdcontrols what percentage of visibility triggers the callback.- Always unobserve elements when done (e.g., after lazy-loading an image).
intersectionRatiotells 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.
