const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
loadMore();
observer.unobserve(entry.target);
}
}, { rootMargin: "200px" });
observer.observe(document.querySelector("#sentinel"));
IntersectionObserver calls you back when an element starts or stops overlapping the viewport, or another root element. It fires at a threshold you choose. The callback is asynchronous, so it doesn't block the page.
Why it beats a scroll listener:
- A scroll listener fires very often, on the main thread.
- Checking visibility with
getBoundingClientRectforces layout each time. - You must throttle the listener yourself.
With IntersectionObserver, the browser computes intersections efficiently. It only notifies you when something changes.
The example watches a sentinel: an empty marker element placed at the end of a list. When the sentinel comes into view, the code loads more items. It uses rootMargin to start loading 200px before the sentinel is visible.
Common uses:
- lazy loading images or components
- infinite scroll
- analytics for impressions (counting which items users actually saw)
- pausing videos or animations that are offscreen
Call unobserve or disconnect when you're done watching.
- IntersectionObserver calls you back asynchronously when visibility crosses a threshold.
- It needs no scroll handlers and causes no forced layout.
rootMargintriggers the callback early, andthresholdsets the visible ratio.- It is used for lazy loading, infinite scroll and impression tracking.
- Call
unobserveordisconnectwhen you are done.
Read more