typescript 41 lines · 7 steps

Lazy-loading images with IntersectionObserver

Defer image loading until each element scrolls near the viewport, with a graceful fallback and a cleanup handle.

Explained by highlit
1type LazyImageOptions = {
2 rootMargin?: string;
3 loadedClass?: string;
4};
5 
6export function initLazyImages(
7 container: ParentNode = document,
8 { rootMargin = '200px 0px', loadedClass = 'is-loaded' }: LazyImageOptions = {}
9): () => void {
10 const targets = container.querySelectorAll<HTMLImageElement>('img[data-src]');
11 
12 if (!('IntersectionObserver' in window)) {
13 targets.forEach((img) => loadImage(img, loadedClass));
14 return () => {};
15 }
16 
17 const observer = new IntersectionObserver((entries, obs) => {
18 for (const entry of entries) {
19 if (!entry.isIntersecting) continue;
20 loadImage(entry.target as HTMLImageElement, loadedClass);
21 obs.unobserve(entry.target);
22 }
23 }, { rootMargin, threshold: 0.01 });
24 
25 targets.forEach((img) => observer.observe(img));
26 
27 return () => observer.disconnect();
28}
29 
30function loadImage(img: HTMLImageElement, loadedClass: string): void {
31 const { src, srcset } = img.dataset;
32 if (!src) return;
33 
34 img.addEventListener('load', () => img.classList.add(loadedClass), { once: true });
35 
36 if (srcset) img.srcset = srcset;
37 img.src = src;
38 
39 delete img.dataset.src;
40 delete img.dataset.srcset;
41}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1IntersectionObserver lets you react to viewport proximity without manual scroll listeners.
  2. 2Feature-detect browser APIs and provide an eager fallback so nothing silently fails.
  3. 3Returning a cleanup function makes side-effecting initializers safe to tear down.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Lazy-loading images with IntersectionObserver — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code