Advertisement
Advanced JavaScript, Browser Storage & Web APIs

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

Short 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.

Save JavaScript mock interview
Advertisement
AModel 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.
Likely follow-ups
  • How would you unobserve an element once it's been handled?
Related topics