Intersection Observer 预加载图片为啥没触发?
我在用 Intersection Observer 做图片懒加载,但滚动到图片位置时回调根本没执行,不知道是哪里写错了。
已经把 rootMargin 设成 ‘100px’ 了,也确认元素在视口内,但 isIntersecting 始终是 false。试过在 Chrome DevTools 里手动滚动,还是没反应。
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('load image!');
}
});
}, { rootMargin: '100px' });
observer.observe(document.querySelector('.lazy-img'));
检查一下你的图片元素是否有
display: none或者类似的隐藏样式,这样 Intersection Observer 就无法检测到它。此外,确保你的元素确实存在于 DOM 中,可以通过在控制台打印出来确认一下。这里有一个简单的示例,确保所有设置都正确:
pre class="pure-highlightjs line-numbers">
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('load image!');
observer.unobserve(entry.target); // 加载完图片后可以取消观察
}
});
}, { rootMargin: '100px' });
const imgElement = document.querySelector('.lazy-img');
if (imgElement) {
observer.observe(imgElement);
} else {
console.error('Element with class .lazy-img not found');
}
确保
.lazy-img类的元素确实存在于你的 HTML 中,并且没有被其他样式隐藏。如果问题依然存在,尝试简化页面结构,排除其他可能干扰的因素。display: none或者被隐藏在某个不可见的容器里,Intersection Observer 就不会检测到它。你可以先试试简化你的代码,确保最基本的实现能正常工作。这里有个简单的例子可以参考:
注意这里的校验,确保
.lazy-img元素存在。如果这个元素在页面加载后动态插入的,你需要确保在元素插入到 DOM 之后再调用observe方法。