🟡 MediumDOM & Events📖 Theory Question

What is IntersectionObserver and how do you use it for lazy loading?

💡

Hint

Detect when elements enter the viewport — no scroll listener, no layout thrashing

Full Answer

// Lazy loading images
const observer = new IntersectionObserver((entries, obs) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src; // load real image
      obs.unobserve(img);        // stop watching this one
    }
  });
}, {
  root: null,          // null = viewport
  rootMargin: '200px', // trigger 200px BEFORE element is visible
  threshold: 0.1       // fire when 10% of element is visible
});

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

// Infinite scroll
const sentinel = document.querySelector('.load-more');
new IntersectionObserver(([entry]) => {
  if (entry.isIntersecting) loadNextPage();
}).observe(sentinel);

// entry properties:
// entry.isIntersecting — true/false
// entry.intersectionRatio — 0 to 1
// entry.boundingClientRect — element position
// entry.target — the observed element
💡 IntersectionObserver is async and non-blocking — no layout thrashing from getBoundingClientRect() in scroll handlers. Far more performant than scroll events.

More DOM & Events Questions

🟢 EasyExplain event delegation and why it is useful.→🟢 EasyWhat is the difference between event.stopPropagation() and event.preventDefault()?→🟢 EasyWhat is the difference between event bubbling and event capturing?→🟢 EasyHow do you create and dispatch Custom Events?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint