IntersectionObserver 是浏览器原生提供的一个构造函数,也是 Intersection Observer API的一个接口,用于异步观察目标元素与其祖先元素或顶级文档视口(viewport)的交叉状态。它可以高效地检测元素是否进入或离开视口,非常适合实现懒加载、无限滚动、广告曝光统计等功能。
class Lazy {
constructor(options = {}) {
this.observer = null;
this.options = {
root: null,
delay: 0,
threshold: 0,
trackVisibility: false,
rootMargin: '0px 0px 200px 0px',
...options,
};
this.init();
}
init() {
const callback = (entries) => {
entries.forEach((entry) => {
const {
isIntersecting,
target,
} = entry;
if (isIntersecting) {
target.src = target.dataset.src;
this.unobserve(target);
} else {
console.log('元素不在视口范围中');
}
});
};
this.observer = new IntersectionObserver(callback, this.options);
}
load(targets) {
targets.forEach((target) => {
this.observe(target);
});
}
observe(target) {
this.observer?.observe(target);
}
unobserve(target) {
this.observer?.unobserve(target);
}
disconnect() {
this.observer?.disconnect();
this.observer = null;
}
};
const lazy = new Lazy();
const imgs = document.querySelectorAll('img');
lazy.load(imgs);
IntersectionObserver 是一个强大的工具通过合理配置和优化,可以显著提升页面性能和用户体验。