Intersection Observer
In one line
The Intersection Observer API efficiently watches elements and calls back when they enter or leave a target (usually the viewport).
In simple words
The Intersection Observer API watches one or more elements and triggers a callback when they intersect (or stop intersecting) a root element — typically the browser viewport. This is the modern, efficient way to implement lazy loading, infinite scroll, and scroll-triggered animations.
Before this API, you would attach a scroll listener and call getBoundingClientRect on every scroll event — expensive and janky. The observer batches checks and only fires when the intersection actually changes, offloading the work to the browser. You configure a threshold (how much of the element must be visible) and optional rootMargin.
Common uses: lazy-load images as they scroll into view, reveal animations on scroll, pause video when scrolled away, and load more content (infinite scroll). It is one of the most practically useful modern web APIs.
Example
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src; // lazy load
observer.unobserve(entry.target);
}
});
}, { threshold: 0.1 });
document.querySelectorAll("img[data-src]").forEach(img => observer.observe(img));Each <img> with a data-src is observed. When 10% of it enters the viewport, the real src is set and observation stops — lazy loading.
Related terms
Related Resources
Related Lessons
- Observers
Learn Intersection and other observers.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.