Lesson 6 of 9
Intersection Observer & Scroll Detection
The Intersection Observer API efficiently detects when HTML elements enter or leave the viewport. It's the modern way to implement lazy loading, infinite scroll, scroll animations, and ad viewability tracking - replacing older, performance-heavy scroll event listeners.
How Intersection Observer Works
Create an observer that watches elements and fires a callback when they intersect the viewport:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Element is visible in viewport
entry.target.classList.add('visible');
}
});
});
observer.observe(document.querySelector('.target'));
Options:
โข threshold: 0.5 - Fire when 50% of element is visible
โข rootMargin: '100px' - Start observing 100px before element reaches viewport (pre-loading)
Use cases:
1. Lazy loading images - Set src from data-src when visible
2. Infinite scroll - Load more content when sentinel element is visible
3. Animate on scroll - Add 'visible' class when element enters viewport
4. Track ad viewability - Report when ad is 50%+ visible for 1+ second
Why not use scroll events?
Scroll events fire 30-60 times per second, causing performance issues. Intersection Observer is asynchronous and optimized by the browser.
Intersection Observer detects visible elements efficiently off the main thread
Tip
Set rootMargin to '200px' in your IntersectionObserver options to start loading images 200px before they enter the viewport. This gives the browser a head start on downloading images, making the page feel faster because images appear already loaded when the user scrolls to them.
Finished this lesson?