Lazy Loading with IntersectionObserver
Load content when it enters the viewport.
Code
JavaScript
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src || img.src;
observer.unobserve(img);
}
});
}, { rootMargin: "50px" });
document.querySelectorAll("img[data-src]").forEach((el) => observer.observe(el));Line-by-line explanation
- 1.IntersectionObserver fires when elements enter viewport.
- 2.isIntersecting true when visible.
- 3.Set img.src from data-src for lazy loading.
- 4.unobserve to stop watching after load.
Expected output
Images load when scrolled into view