JavaScript Interview Question #167

What is IntersectionObserver?

Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced

Quick Interview Answer

IntersectionObserver asynchronously reports when a target element enters or leaves the intersection of a root viewport or ancestor. It is commonly used for lazy loading, visibility tracking, and triggering work when content approaches the viewport.

Detailed Explanation

IntersectionObserver asynchronously reports when a target element enters or leaves the intersection of a root viewport or ancestor. It is commonly used for lazy loading, visibility tracking, and triggering work when content approaches the viewport.

It is usually preferable to continuously calculating visibility in a high-frequency scroll handler because the browser can manage observation more efficiently.

Code Example

const observer = new IntersectionObserver(entries => {
    for (const entry of entries) {
        if (entry.isIntersecting) {
            console.log("Visible:", entry.target);
            observer.unobserve(entry.target);
        }
    }
});

observer.observe(
    document.querySelector("#section")
);