JavaScript › Browser Storage & Web APIs

What does the Intersection Observer API do and why is it preferred over scroll event listeners?

Advanced

Answer

IntersectionObserver asynchronously watches when a target element enters or leaves the viewport (or another container), without the performance cost of firing on every scroll event and manually computing element positions.
const observer = new IntersectionObserver((entries) => {
  entries.forEach(e => { if (e.isIntersecting) loadImage(e.target); });
});
observer.observe(document.querySelector('img.lazy'));
Real-world example Implementing lazy-loading images or infinite scroll without janky scroll-handler performance.

Common follow-ups: How would you unobserve an element once it's been handled?