说说你对 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);
关键点
root为滚动容器(默认视口);rootMargin扩展判定边界(如提前 200px 触发懒加载);threshold是交叉比例阈值数组,可设置多个;- 回调在微任务/空闲时批量触发,不是逐帧轮询;
- 返回
isIntersecting、intersectionRatio、boundingClientRect、time; unobserve/disconnect释放。
场景
图片/组件懒加载、无限滚动哨兵、曝光埋点、广告可见性、滚动动画触发。
注意
需 polyfill 兼容老浏览器;不能替代需要精确滚动位置计算的场景。