0

I'm trying to lazy-load images using IntersectionObserver. However, all images are loaded right away, before they enter the viewport via scroll. I know this because I look in the Network tab and Inspector to see where they're at before I scroll down.

I have tried this in Windows Chrome.

https://jsfiddle.net/Ln4gv7mw/

HTML:

<img src="placeholder.png" data-src="image1">
<img src="placeholder.png" data-src="image2">
<img src="placeholder.png" data-src="image3">

JAVASCRIPT

let observer = new IntersectionObserver(
(entries, observer) => { 
entries.forEach(entry => {
    /* Placeholder replacement */
    entry.target.src = entry.target.dataset.src;
    observer.unobserve(entry.target);
  });
}, 
{rootMargin: "0px 0px 0px 0px"});

document.querySelectorAll('img').forEach(img => { observer.observe(img) });
user984003
  • 28,050
  • 64
  • 189
  • 285

1 Answers1

0

I had to check for entry.isIntersecting. https://jsfiddle.net/81w79sg3/

I also set rootMargin to 100px, which makes the images load before they scroll into view. Rootmargin doesn't work in the jsfiddle (something about the iframe, but works on a real page)

let observer = new IntersectionObserver(
(entries, observer) => { 
entries.forEach(entry => {
    if(entry.isIntersecting){
      entry.target.src = entry.target.dataset.src;
      observer.unobserve(entry.target);
    }
  });
});

document.querySelectorAll('img').forEach(img => { observer.observe(img) });
user984003
  • 28,050
  • 64
  • 189
  • 285