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

时间:2018-11-08 18:36:34

标签: 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.');
}

这似乎可以正常工作,并且只要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);

1 个答案:

答案 0 :(得分:7)

这是默认行为。实例化IntersectionObserver的实例时,将触发callback

建议防止这种情况。

entries.forEach(entry => {
  if (entry.intersectionRatio > 0) {
    entry.target.classList.add('in-viewport');
  } else {
    entry.target.classList.remove('in-viewport');
  }
});

我还发现本文和文档非常有帮助,特别是关于IntersectionObserverEntry的intersectionRatioisIntersecting属性。

·https://www.smashingmagazine.com/2018/01/deferring-lazy-loading-intersection-observer-api/

·https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver

·https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry