Introduction
The Intersection Observer API is a modern web API used in frontend development to efficiently detect when an element enters or exits the viewport. It is widely used for implementing lazy loading, infinite scrolling, and visibility tracking without relying on expensive scroll event listeners.
Lazy loading is a performance optimization technique where images, videos, or other resources are loaded only when they are needed, typically when they come into view on the user’s screen.
In practical web development:
Intersection Observer tracks element visibility
Lazy loading improves performance by deferring resource loading
This combination helps build fast, responsive, and user-friendly web applications.
How Intersection Observer Works
The API allows developers to create an observer object that monitors target elements and triggers a callback when their visibility changes relative to a root container (usually the viewport).
Basic Syntax
const observer = new IntersectionObserver(callback, options);
callback: Function executed when visibility changes
options: Configuration such as threshold and root margin
Step-by-Step Lazy Loading Example
Step 1: HTML Setup
<img data-src="image.jpg" class="lazy-image" alt="Example Image" />
Here, the actual image URL is stored in data-src instead of src.
Step 2: JavaScript Implementation
const images = document.querySelectorAll('.lazy-image');
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
images.forEach(img => observer.observe(img));
Step 3: Options Configuration
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
};
root: viewport or parent container
rootMargin: margin around root
threshold: percentage of visibility to trigger callback
Real-Life Examples and Scenarios
Scenario 1: Image Lazy Loading
Instead of loading all images at once:
Images load only when visible
Reduces initial page load time
Scenario 2: Infinite Scrolling
Used in social media feeds or blogs:

Join the conversation! Your thoughts help the community grow.