← 返回完整题库
JavaScript中等

说说你对 IntersectionObserver 的理解

参考答案

作用

异步观察元素与视口(或指定 root)的交叉状态,不阻塞主线程、无需监听 scroll。

const io = new IntersectionObserver((entries) => {
  entries.forEach(en => console.log(en.isIntersecting, en.intersectionRatio));
}, { root: null, threshold: [0, 0.5, 1], rootMargin: "100px" });
io.observe(el);

关键点

  1. root 为滚动容器(默认视口);rootMargin 扩展判定边界(如提前 200px 触发懒加载);
  2. threshold 是交叉比例阈值数组,可设置多个;
  3. 回调在微任务/空闲时批量触发,不是逐帧轮询;
  4. 返回 isIntersecting、intersectionRatio、boundingClientRect、time;
  5. unobserve / disconnect 释放。

场景

图片/组件懒加载、无限滚动哨兵、曝光埋点、广告可见性、滚动动画触发。

注意

需 polyfill 兼容老浏览器;不能替代需要精确滚动位置计算的场景。

本题来自 计算机知识面试题库,共 921 道题。