← 中文资源

简体中文版本

IntersectionObserver 监听元素可见性

用 IntersectionObserver 取代滚动监听:元素即将进入视口才懒加载,rootMargin 提前触发,unobserve 做一次性加载,页面隐藏时 disconnect 释放引用。

阅读英文原文

实现说明

循环只出现在 for (const entry of entries),它的每次迭代处理一个元素。 顶层就这几处状态:lazyImages、observer。

使用要点

  • 用到了 document、window、IntersectionObserver,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 守卫 !entry.isIntersecting 命中后立刻用提前的 continue 结束这一轮。
  • 直接运行文件,输出会带上标签,比如 loading:——输出的每一行都能指回产生它的那次调用。

常见问题

「IntersectionObserver 监听元素可见性」能在裸 Node.js 里跑吗?

不能——document、window 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

核心语句

window.addEventListener('pagehide', () => observer.disconnect(), { once: true });
lazyImages.forEach((img) => observer.observe(img));
(entries) => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;
    const img = entry.target;
    img.src = img.dataset.src; // 即将进入视口才真正发起加载
    console.log('loading:', img.dataset.src, 'ratio', entry.intersectionRatio);
    observer.unobserve(img); // 一次性懒加载:触发即取消观察
  }
},

代码示例

// IntersectionObserver:元素与视口相交时被动通知,取代滚动事件监听
const lazyImages = document.querySelectorAll('img[data-src]');

const observer = new IntersectionObserver(
  (entries) => {
    for (const entry of entries) {
      if (!entry.isIntersecting) continue;
      const img = entry.target;
      img.src = img.dataset.src; // 即将进入视口才真正发起加载
      console.log('loading:', img.dataset.src, 'ratio', entry.intersectionRatio);
      observer.unobserve(img); // 一次性懒加载:触发即取消观察
    }
  },
  { rootMargin: '200px 0px', threshold: 0.01 }, // 提前 200px 预载
);
lazyImages.forEach((img) => observer.observe(img));

// 组件卸载/页面隐藏时断开,避免观察器持有已卸载 DOM 的引用
window.addEventListener('pagehide', () => observer.disconnect(), { once: true });