IntersectionObserver Lazy Image Loading
Load images as they approach the viewport with IntersectionObserver: rootMargin gives lead time, each image is unobserved after load, teardown calls disconnect.
Code
// IntersectionObserver: 图片接近视口时才开始加载(懒加载)
function observeLazyImages(container: ParentNode): IntersectionObserver {
const images = container.querySelectorAll<HTMLElement>('img[data-src]');
const observer = new IntersectionObserver(
(entries, obs) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const img = entry.target as HTMLImageElement;
const src = img.dataset.src; // data-src 属性的值
if (src) img.src = src;
img.removeAttribute('data-src');
obs.unobserve(img); // 每张图只加载一次
}
},
{ rootMargin: '200px 0px', threshold: 0.01 },
);
images.forEach((img) => observer.observe(img));
return observer;
}
// 列表重渲染或组件卸载时断开观察,避免持有已移除的节点
function teardown(observer: IntersectionObserver): void {
observer.disconnect();
}Inside the snippet
IntersectionObserver Lazy Image Loading reduces to the functions observeLazyImages and teardown.
Repetition is confined to for (const entry of entries) — the rest of the file is straight-line.
What to watch for
- The snippet leans on
IntersectionObserver— browser-only surfaces a bare Node process cannot provide. - The guard
!entry.isIntersectingshort-circuits the flow with an earlycontinuewhen its condition holds.
Using it
The primary signature is function observeLazyImages(container: ParentNode)
Key statements
images.forEach((img) => observer.observe(img));
(entries, obs) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const img = entry.target as HTMLImageElement;
const src = img.dataset.src; // data-src 属性的值
if (src) img.src = src;
img.removeAttribute('data-src');
obs.unobserve(img); // 每张图只加载一次
}
},
Interactive Tools for This Topic
Base64 Image PreviewPreview a Base64 or data URI image, detect its MIME type from the magic bytes, and see the decoded byte size without uploading anything.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.
FAQ
- Does IntersectionObserver Lazy Image Loading run in plain Node.js?
- No — it touches `IntersectionObserver`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.