👁️
Intersection Observer — Detect Element Visibility Without Scroll Events
Performance-friendly implementation for lazy loading, infinite scroll, animation triggers
Why Better Than scroll Events
scroll fires dozens to hundreds of times per second. Each getBoundingClientRect() call triggers reflow.
Intersection Observer: browser-optimized timing, no reflow, more efficient than requestAnimationFrame.
Options
rootMargin: '100px' detects 100px below viewport — for "start loading before scrolling" in lazy loading.
Practical Patterns
Image lazy loading, Infinite scroll (observe last item → load next page), Scroll animations (fade-in on visibility).
Key Points
1
Create observer with new IntersectionObserver(callback, options)
2
Register targets with observer.observe(element)
3
Check viewport entry with entry.isIntersecting
4
Expand detection area with rootMargin — pre-load/animate
Use Cases
Image lazy loading — set src when near viewport
Infinite scroll — fetch next page when last item becomes visible