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.

TypescriptData Fetching

Code

typescriptsnippet
26 lines
// 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.isIntersecting short-circuits the flow with an early continue when 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

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.