40

我对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()时被调用,但在页面最初加载时也会触发一次,这会触发 `console.log('observer trigger.');.lazy-loadcallback()

页面加载时是否有理由触发此回调?或者我如何实施这个有错误?

编辑:将代码更改为以下代码仍会在页面加载时触发回调。

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);
4

2 回答 2

64

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

建议提防这种情况。

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

我还发现这篇文章以及文档非常有帮助,特别是关于 IntersectionObserverEntry 上的intersectionRatioorisIntersecting属性。

· 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

于 2018-11-20T02:14:00.277 回答
0

听起来很简单,我能够通过以下方式解决问题

  1. 添加阈值比较条件
  2. 为观察者的初始化增加一点延迟
    const options = {
      threshold: 1.0,
    };

      setTimeout(() => {
        observer = new IntersectionObserver(([entry]) => {
          console.log("OBSERVER TRIGGERED 1");

          if (
            entry &&
            entry.isIntersecting &&
            entry.intersectionRatio >= options.threshold
          ) {
            console.log("OBSERVER TRIGGERED 2");
          }
        }, options);

        observer.observe(observerRef.value);
      }, 2000);

我还建议临时将可观察元素的背景颜色更改为:

.observer {
  background-color: red;
}

并进行页面刷新。这样,您实际上可能会在屏幕上看到红色背景闪烁,从而触发事件。

现在,在你向我扔西红柿之前——就我而言——我的网页上有十几个视频。视频 HTML 元素不会立即“扩展”,因为浏览器需要下载有关海报图像的信息。因此页面已加载,但视频仍在加载。添加轻微延迟解决了问题,因此浏览器有时间扩展视频内容。

于 2021-11-17T18:24:38.653 回答