IntersectionObserver回调在页面加载时立即触发

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 的intersectionRatioisIntersecting属性。

· 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

  • 我认为最好依赖“isIntersecting”,因为有时我见过一些“intersectingRatio”为零但“isIntersecting”为真的情况——在我的例子中这是正确的行为。 (7认同)