When to Use
- Lazy loading images or heavy components.
- Implementing infinite scrolling interfaces.
- Reporting visibility of advertisements.
- Triggering animations when elements scroll into view.
When NOT to Use
- Tracking precise pixel-by-pixel scrolling (use passive scroll listeners).
- Detecting overlaps of elements that do not involve the viewport/scroll container.
Code Examples
Lazy Loading Images Efficiently
This creates a single observer that tracks multiple images. As soon as an image is within 100px of the viewport, its actual source is loaded, and it is unobserved to free memory.
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
obs.unobserve(img); // Stop observing once loaded
}
});
}, { rootMargin: '100px' });
document.querySelectorAll('img.lazy').forEach(img => observer.observe(img));