如何在div滚动元素内延迟加载图像

问题描述 投票:0回答:2

如何在有溢出的 #panel-scroll 中延迟加载图像:scroll;我尝试了这个代码示例,但它给了我意外的令牌错误。谁能帮我解决这个问题吗?

document.addEventListener("DOMContentLoaded", function() {
  var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));

  if ("IntersectionObserver" in getElementById('#panel-scroll') {
    let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          let lazyImage = entry.target;
          lazyImage.src = lazyImage.dataset.src;
          lazyImage.srcset = lazyImage.dataset.srcset;
          lazyImage.classList.remove("lazy");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    });

    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage);
    });
  } else {
    // Possibly fall back to event handlers here
  }
});  
javascript lazy-loading
2个回答
0
投票

我会考虑以下更新:

  1. 使用
    getElementById
    时,不应使用“#”符号,因为这是不正确的。应该是:
const scrollablePanel = document.getElementById('panel-scroll');
  1. 您可以指定
    IntersectionObserver
    的根作为选项:
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
  ...
}, { root: scrollablePanel });

0
投票

document.addEventListener("DOMContentLoaded", function() {
  const scrollContainer = document.querySelector('#panel-scroll');
  const lazyImages = [...scrollContainer.querySelectorAll("img.lazy")];

  if ("IntersectionObserver" in window) {
    let observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          let img = entry.target;
          img.src = img.dataset.src;
          img.srcset = img.dataset.srcset;
          img.classList.remove("lazy");
          observer.unobserve(img);
        }
      });
    }, { root: scrollContainer });

    lazyImages.forEach(img => observer.observe(img));
  } else {
    // Fallback: Load all images if IntersectionObserver is not supported
    lazyImages.forEach(img => {
      img.src = img.dataset.src;
      img.srcset = img.dataset.srcset;
    });
  }
});

  1. #panel-scroll
     作为根初始化 
    IntersectionObserver
  2. 使用滚动容器中的“lazy”类观察每个图像。
  3. 当图像在滚动容器中可见时加载图像。
  4. 为不支持
    IntersectionObserver
    的浏览器提供后备。

仅当图像靠近可滚动

#panel-scroll
div 的视口时,此脚本才会有效地加载图像,从而增强性能和用户体验。

© www.soinside.com 2019 - 2024. All rights reserved.