问题描述
我对 IntersectionObserver API 很陌生,我一直在尝试这段代码:
I'm very new to the IntersectionObserver API, and I've been experimenting with this code:
let target = document.querySelector('.lazy-load');
let options = {
root: null,
rootMargin: '0px',
threshold: 0
}
let observer = new IntersectionObserver(callback, options);
observer.observe(target);
function callback() {
console.log('observer triggered.');
}
这似乎应该可以正常工作,并且callback()
会在.lazy-load
元素进入视口时被调用,但是callback()
也会在页面首次加载时触发一次,从而触发`console.log(' .")
This seems to work as it should, and callback()
is called whenever .lazy-load
element enters the viewport, but callback()
also fires once when the page is initially loaded, which triggers `console.log('observer triggered.');
加载页面时是否有触发此回调的原因?还是我在实施此方法时有错误?
Is there a reason for this callback to be triggered when the page loads? Or is there a mistake in how I'm implementing this?
将代码更改为以下内容仍会在页面加载时触发回调.
let target = document.querySelector('.lazy-load');
let options = {
root: null,
rootMargin: '0px',
threshold: 0
}
let callback = function(entries, observer) {
entries.forEach(entry => {
console.log('observer triggered.');
});
};
let observer = new IntersectionObserver(callback, options);
observer.observe(target);
推荐答案
这是默认行为.实例化IntersectionObserver的实例时,将触发callback
.
That is the default behaviour. When you instantiate an instance of the IntersectionObserver, the callback
will be fired.
建议防止这种情况.
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
entry.target.classList.add('in-viewport');
} else {
entry.target.classList.remove('in-viewport');
}
});
我还发现本文和文档非常有帮助,特别是关于IntersectionObserverEntry上的intersectionRatio
或isIntersecting
属性.
Also I found this article as well as the docs to be very helpful, specifically about the intersectionRatio
or isIntersecting
properties on the IntersectionObserverEntry.
· https://www.smashingmagazine. com/2018/01/deferring-lazy-loading-intersection-observer-api/
· https://developer.mozilla.org/zh-CN /docs/Web/API/IntersectionObserver
· https://developer.mozilla.org/zh-CN /docs/Web/API/IntersectionObserverEntry
这篇关于IntersectionObserver回调在页面加载时立即触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!