IntersectionObserver Detection for Lazy Loading

Detect IntersectionObserver support for implementing lazy loading, infinite scroll, and visibility-based animations without scroll event listeners.

DOM

Detailed Explanation

IntersectionObserver Detection

The IntersectionObserver API provides an efficient way to observe when elements enter or leave the viewport (or another element). It eliminates the need for expensive scroll event listeners and manual bounding rect calculations.

Detection

const hasIntersectionObserver =
  typeof IntersectionObserver !== 'undefined';

Basic Usage

const observer = new IntersectionObserver(
  (entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        // Element is visible
        loadImage(entry.target);
        observer.unobserve(entry.target);
      }
    });
  },
  {
    root: null,        // viewport
    rootMargin: '100px', // load 100px before visible
    threshold: 0.1,    // 10% visible triggers callback
  }
);

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

Performance Benefits

Approach CPU Cost Accuracy
scroll + getBoundingClientRect High (every frame) Manual
IntersectionObserver Low (browser-optimized) Automatic

Common Patterns

  1. Lazy loading images: Load images only when they approach the viewport
  2. Infinite scroll: Detect when a sentinel element becomes visible to load more content
  3. Ad impression tracking: Report when an ad is actually visible to the user
  4. Sticky headers: Detect when an element passes a scroll threshold
  5. Entrance animations: Trigger CSS animations when elements scroll into view

Polyfill

For older browsers, the official W3C polyfill is available at intersection-observer on npm, providing identical API behavior using scroll events internally.

Use Case

Critical for performance-optimized web applications. Used for lazy loading images and components, implementing infinite scroll feeds, tracking ad viewability, triggering scroll-based animations, and virtualizing long lists.

Try It — Browser Feature Detector

Open full tool