数据预览属性中的延迟加载图像

时间:2018-07-03 09:57:49

标签: javascript jquery lazy-loading

当前,我正在通过以下代码实现延迟加载图片,该代码来自google。

<img class="lazy" src="placeholder-image.jpg" data-src="image-to-lazy-load-1x.jpg" data-srcset="image-to-lazy-load-1x.jpg 1x" alt="I'm an image!">

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

  if ("IntersectionObserver" in window) {
    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 a more compatible method here
  }
});

现在我需要将此技术应用于<li><li>  进入滑块内。

 <li data-preview="sliders/my-image.jpg" data-ulr-link="#">  some html </li>

我如何在data-preview属性中为图像应用延迟加载。

0 个答案:

没有答案