Intersection Observer as Event Alternative
You'll learn why Intersection Observer is a smarter, more efficient way to detect when elements become visible than using scroll events.
The Problem with Scroll Events
When you need to know if an element has scrolled into view (for lazy-loading images, animations, infinite scroll, etc.), your first instinct might be to attach a scroll event listener. However, scroll events fire constantly as the user scrolls—potentially hundreds of times per second. Each time, you'd need to calculate element positions using methods like getBoundingClientRect(), which forces the browser to recalculate layout. This is expensive and can cause janky, stuttering scrolling.
Enter Intersection Observer
Intersection Observer is a modern API specifically designed to efficiently watch when elements enter or leave the viewport (or any ancestor container). Instead of constantly checking positions during scroll, you register a callback that only fires when visibility actually changes.
Think of it like the difference between constantly asking "Are we there yet?" versus being told "I'll let you know when we arrive." The browser handles the heavy lifting and only notifies you when something meaningful happens.
Basic Pattern
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Element is now visible!
console.log('Element entered viewport');
}
});
});
const element = document.querySelector('.lazy-image');
observer.observe(element);
The browser efficiently tracks visibility without blocking the main thread, and you can observe multiple elements with a single observer. When you're done, use observer.unobserve(element) or observer.disconnect().
Key Takeaway: Use Intersection Observer instead of scroll events for visibility detection—it's dramatically more performant, easier to use, and specifically designed for this purpose.