Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Imagine you're reading a long article and images only load when you scroll to them - that's Intersection Observer at work! It watches elements and tells you when they become visible on the screen. No more constantly checking!
Listen to scroll events → Check position thousands of times → Slow performance → Battery drain 🔋
Browser watches for you → Only notifies when needed → Fast performance → Happy battery! 🎉
🎉 Intersection Observer triggers!
→ Starts loading the image
👋 Intersection Observer knows!
→ Can stop animations, etc.
// Create an observer
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Element is visible!
const img = entry.target;
img.src = img.dataset.src; // Load the image
observer.unobserve(img); // Stop watching
}
});
});
// Watch all lazy images
const lazyImages = document.querySelectorAll('img[data-src]');
lazyImages.forEach(img => observer.observe(img));const options = {
// Root element (null = viewport)
root: null,
// Margin around root (like CSS margin)
rootMargin: '0px',
// Examples:
// rootMargin: '50px' - trigger 50px before entering
// rootMargin: '-100px' - trigger 100px after entering
// Threshold: 0-1 (how much visible)
threshold: 0.5
// threshold: 0 - trigger immediately when any part visible
// threshold: 0.5 - trigger when 50% visible
// threshold: 1 - trigger when fully visible
// threshold: [0, 0.5, 1] - trigger at multiple points
};
const observer = new IntersectionObserver(callback, options);Instagram, Pinterest
Load images only when visible
Twitter, Facebook feeds
Load more as you scroll
Modern websites
Fade in as you scroll down
Track which content users view
Know what's popular
No constant scroll event listening - browser handles it efficiently!
Only load resources when needed - great for mobile users!
Simple API - create observer, watch elements, done!
Less JavaScript execution = longer battery life on mobile!
observer.unobserve(element) after you're done watching an element to prevent memory leaks!Watches elements and tells you when they become visible
Better performance, saves bandwidth, battery friendly!
Lazy loading, infinite scroll, animations, analytics
Create observer → Watch elements → Handle callbacks!