IntersectionObserver on IE, Edge

IntersectionObserver is fairly new, experimental API, and at this moment is not fully supported by all browsers.

It will have many uses, but for now the most prominent one is lazy-loading your images, that is if you have them plenty on your website. It is recommended by Google if you audit your website with Lighthouse.

Now, there are several snippets around the web suggesting its usage but I think none of them are 100% vetted. For example I'm trying to use this one. It works like a charm on Chrome, Firefox and Opera but it doesn't work on IE and 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);
    }

  });
}

To be more precise, the code should recognize if browser supports IntersectionObserver and if NOT it should immediately load all images without utilizing the API and write to console that IntersectionObserver is not supported. So, the snippet above fails to do that.

As far as my investigation goes, when testing with IE 11 and Edge 15, they spit an error to console that they don't recognize forEach, despite the fact that they should support it.

I've tried to shim forEach, and even replace forEach with good old for, but I can't get this snippet to work on IE and Edge.

Any thoughts?

Answers:

Answer

After some tests, I found the reason.

First, I let the observer observe document.body, it works. Then I guess the observer can't observe empty elements, so I set 1px border on the element I want to observe, and then it works.

This may be a bug on Edge, because Chrome and Firefox can both observe empty elements.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.