实现说明
全部逻辑都在函数 observeLazyImages、teardown中。
在这里做循环的是 for (const entry of entries)。
使用要点
- 这是浏览器侧代码——
IntersectionObserver在 Node 里解析不到。 - 守卫
!entry.isIntersecting成立时借助提前的continue直接离开。
常见问题
「IntersectionObserver 懒加载图片」能在裸 Node.js 里跑吗?
不能——这类 API 归浏览器环境所有(IntersectionObserver),Node 里不存在。请在页面或 DevTools 控制台中运行。
主签名形如 function observeLazyImages(container: ParentNode)
核心语句
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); // 每张图只加载一次
}
},
代码示例
// 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();
}