user1431398
user1431398

Reputation:

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(). 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);
    });
  }
});

Console error message

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

Thanks for any tips!

Upvotes: 0

Views: 410

Answers (1)

user1431398
user1431398

Reputation:

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.

Try document.documentElement or document.body instead of document

This may be related to document being an HTMLDocument, but the other two being HTMLElements each. Their prototype chains diverge after Node. Perhaps Safari can’t handle HTMLDocuments being roots in IntersectionObservers.

Further reading provided by @SurajRao: IntersectionObserver not working in Safari or iOS

Upvotes: 1

Related Questions