Hiprup

What is IntersectionObserver?

IntersectionObserver efficiently watches when an element enters or leaves the viewport (or a container), without expensive scroll listeners.

  • How — observe an element and get a callback when its visibility crosses a threshold.

  • Why — far cheaper than listening to scroll and measuring positions manually.

Common uses: lazy-loading images, infinite scroll, and triggering animations when content appears.

// Lazy loading images
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src; // Load real image
      observer.unobserve(img);   // Stop observing
    }
  });
}, {
  rootMargin: '200px', // Start loading 200px before visible
  threshold: 0         // Trigger as soon as any pixel is visible
});

document.querySelectorAll('img[data-src]').forEach(img => {
  observer.observe(img);
});

// Infinite scroll
const sentinel = document.getElementById('sentinel');
const scrollObserver = new IntersectionObserver(([entry]) => {
  if (entry.isIntersecting) {
    loadMoreItems();
  }
});
scrollObserver.observe(sentinel);

The observer watches elements and fires the callback when they enter/exit the viewport. rootMargin: '200px' starts triggering 200px before the element is visible (preloading). unobserve stops watching after the image is loaded. The sentinel element for infinite scroll triggers loading when it becomes visible.

Two practical use cases: lazy loading (images) and infinite scroll (load more). rootMargin for preloading is the key configuration. unobserve after loading prevents unnecessary callbacks. Better than scroll events (no main thread blocking).

What is IntersectionObserver? | Hiprup