简体   繁体   English

Javascript TypeError:仅在 Safari 中使用 IntersectionObserver() 时出现类型错误

[英]Javascript TypeError: Type error when using IntersectionObserver() only in Safari

I can't figure out why Safari (13.0.2) is throwing a TypeError: Type error when using IntersectionObserver() .我不明白为什么 Safari (13.0.2) 在使用IntersectionObserver()TypeError: Type error The other major browsers don't.其他主要浏览器没有。

document.addEventListener("DOMContentLoaded", () => {

  const lazyImages = [].slice.call(document.querySelectorAll("img"));

  if ("IntersectionObserver" in window) {
    const observerOptions = {
      root: document,
      rootMargin: '500px'
    }

    let lazyImageObserver = new IntersectionObserver((entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          let lazyImage = entry.target;
          lazyImage.src = lazyImage.getAttribute("data-lazyload-src");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    }, observerOptions);

    lazyImages.forEach((lazyImage) => {
      lazyImageObserver.observe(lazyImage);
    });
  }
});

控制台错误信息

Line 138 is let lazyImageObserver = new IntersectionObserver((entries, observer) => {第 138 行是let lazyImageObserver = new IntersectionObserver((entries, observer) => {

Thanks for any tips!感谢您的任何提示!

I don't know how to mark a comment as answer.我不知道如何将评论标记为答案。 Anyways, the suggestion in @user4642212's comment to use document.body instead of just document , works.无论如何,@user4642212 的评论中关于使用document.body而不仅仅是document的建议是有效的。

Try document.documentElement or document.body instead of document尝试document.documentElementdocument.body而不是document

This may be related to document being an HTMLDocument , but the other two being HTMLElements each.这可能与documentHTMLDocument相关,但另外两个分别是HTMLElements Their prototype chains diverge after Node .它们的原型链在Node之后出现分歧。 Perhaps Safari can't handle HTMLDocuments being roots in IntersectionObservers .也许 Safari 无法处理HTMLDocuments作为IntersectionObserversroots

Further reading provided by @SurajRao: IntersectionObserver not working in Safari or iOS @SurajRao 提供的进一步阅读: IntersectionObserver not working in Safari 或 iOS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM