0

I am working on website at the moment, that has some native lazy loading of images using IntersectionObserver the images that I am trying to load are loaded in via ajax as a result I don't think they are "loaded" into DOM on page load, and therefore the images cannot be lazyloaded, by lazy load codes looks like this,

const io = new IntersectionObserver((entries, observer) => {
    // console.log(entries)
    entries.forEach(entry => {
      console.log('');

      if (entry.isIntersecting) {

        console.log('intersecting');

        const img = entry.target;
        const src = img.getAttribute('data-lazy');

        img.setAttribute('src', src);
        img.classList.add('fade');

        observer.disconnect();
      }
    });

Is it possible to lazy load images that are part of content that is loaded via ajax?

Udders
  • 6,914
  • 24
  • 102
  • 194
  • Can you show us how you fetch the images and put them into the document? Also `observer.disconnect()` immediately stops all activity after it has been called. Maybe you meant [`observer.unobserve(entry.target)`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/unobserve)? – Emiel Zuurbier Feb 18 '20 at 22:09

1 Answers1

2

Yes, it is possible. After you fetch your data and update your DOM, you need to call your observer again.

const io = new IntersectionObserver((entries, observer) => {
  // console.log(entries)
  entries.forEach(entry => {
    console.log('');

    if (entry.isIntersecting) {

      console.log('intersecting');

      const img = entry.target;
      const src = img.getAttribute('data-lazy');

      img.setAttribute('src', src);
      img.classList.add('fade');

      observer.disconnect();
    }
  });
});

io.observe(document.querySelectorAll('ímg'));

const fethNewData = () => {
  // any ajax call
  window.fetch().then((html) => {
    //update DOM
    document.querySelector('body').innerHTML = html;
    //call observe again
    io.observe(document.querySelectorAll('ímg'));
  })
};
hurricane
  • 6,521
  • 2
  • 34
  • 44