IntersectionObserver Watches Element Visibility
Replace scroll listeners with IntersectionObserver: lazy-load images once near the viewport, pre-trigger with rootMargin, and disconnect on teardown.
Code
// 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 });What the code does
Iteration happens inside for (const entry of entries) — everything outside it runs once.
The file’s state is a handful of top-level bindings: lazyImages, observer.
What to watch for
- This is browser-side code —
document,window,IntersectionObserverwill not resolve in Node. - The guard
!entry.isIntersectingshort-circuits the flow with an earlycontinuewhen its condition holds.
Using it
Running the file prints labeled results such as loading: — each operation’s effect is visible in the output.
Key statements
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); // 一次性懒加载:触发即取消观察
}
},
Interactive Tools for This Topic
FAQ
- Does IntersectionObserver Watches Element Visibility run in plain Node.js?
- No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.