【问题标题】:IntersectionObserver and ajax loaded contentIntersectionObserver 和 ajax 加载的内容
【发布时间】:2020-02-18 21:16:34
【问题描述】:

我目前正在网站上工作,该网站使用IntersectionObserver 对图像进行了一些本机延迟加载,我尝试加载的图像是通过 ajax 加载的,因此我认为它们没有被“加载”在页面加载时进入 DOM,因此图像不能被延迟加载,延迟加载代码看起来像这样,

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

是否可以延迟加载属于通过 ajax 加载的内容的一部分的图像?

【问题讨论】:

  • 您能告诉我们您是如何获取图像并将它们放入文档中的吗?此外,observer.disconnect() 在被调用后会立即停止所有活动。也许你的意思是observer.unobserve(entry.target)

标签: javascript lazy-loading intersection-observer


【解决方案1】:

是的,这是可能的。获取数据并更新 DOM 后,您需要再次调用观察者。

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'));
  })
};

【讨论】:

    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2017-11-12
    • 2011-10-31
    相关资源
    最近更新 更多