IE,Edge上的IntersectionObserver

Vil*_*ila 2 javascript foreach internet-explorer microsoft-edge intersection-observer

IntersectionObserver是一个相当新的实验性API,目前尚不受所有浏览器的完全支持

它将有很多用途,但目前最主要的用途是延迟加载图像,也就是说,如果您在网站上拥有大量图像。它是由谷歌建议,如果你审计你的网站灯塔

现在,网络上有几条代码片段提示了其用法,但我认为没有一个经过100%审查。例如,我正在尝试使用这个。它在Chrome,Firefox和Opera上像超级按钮一样工作,但在IE和Edge上不起作用。

const images = document.querySelectorAll('img[data-src]');
const config = {
  rootMargin: '50px 0px',
  threshold: 0.01
};

let observer;

if ('IntersectionObserver' in window) {
  observer = new IntersectionObserver(onChange, config);
  images.forEach(img => observer.observe(img));
} else {
  console.log('%cIntersection Observers not supported', 'color: red');
  images.forEach(image => loadImage(image));
}

const loadImage = image => {
  image.classList.add('fade-in');
  image.src = image.dataset.src;
}

function onChange(changes, observer) {
  changes.forEach(change => {
    if (change.intersectionRatio > 0) {
      // Stop watching and load the image
      loadImage(change.target);
      observer.unobserve(change.target);
    }

  });
}
Run Code Online (Sandbox Code Playgroud)

更准确地说,该代码应识别浏览器是否支持IntersectionObserver,如果不支持,则应立即加载所有图像而不使用API​​并写入IntersectionObserver不支持的控制台。因此,上面的代码片段无法做到这一点。

据我调查,在使用IE 11和Edge 15进行测试时forEach,尽管他们应该支持它,但他们还是吐出了一个他们无法识别的控制台错误。

我尝试使forEach趋于平滑,甚至替换forEach为old old for,但无法在IE和Edge上使用此代码段。

有什么想法吗?

zho*_*ujy 5

经过一些测试,我找到了原因。

首先,我让观察者观察document.body,它起作用。然后,我想观察者无法观察到空元素,因此我在要观察的元素上设置了1px边框,然后它起作用了。

这可能是Edge上的错误,因为Chrome和Firefox都可以观察到空元素。

  • 为了准确,空元素意味着它们的宽度和高度都为0。因此,请设置css`min-width:1px;。最小高度:1px也可以。 (3认同)