rpi*_*var 10 javascript lazy-loading intersection-observer
我是IntersectionObserver API的新手,并且一直在尝试以下代码:
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.');
}
Run Code Online (Sandbox Code Playgroud)
这似乎可以正常工作,并callback()在.lazy-load元素进入视口时调用,但是callback()在页面最初加载时也会触发一次,从而触发“ console.log('观察者被触发”)。
页面加载时是否有触发此回调的原因?还是我执行此方法有误?
编辑:将代码更改为以下内容仍会在页面加载时触发回调。
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);
Run Code Online (Sandbox Code Playgroud)
sne*_*mer 19
这是默认行为。当您实例化IntersectionObserver的实例时,callback将被触发。
建议防止这种情况。
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
entry.target.classList.add('in-viewport');
} else {
entry.target.classList.remove('in-viewport');
}
});
Run Code Online (Sandbox Code Playgroud)
我也发现本文和文档非常有帮助,特别是关于IntersectionObserverEntry 的intersectionRatio或isIntersecting属性。
· 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