通过延迟加载JavaScript删除类

时间:2019-06-14 01:32:12

标签: javascript html css lazy-loading

我正在尝试将某些图像延迟加载到网站上。我遇到的问题是必须删除该类才能使延迟加载正常工作,但我仍然希望图像使用CSS属性。有人可以帮忙吗?

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

  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("Images");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    });

    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage);
    });
  } else {
    // Possibly fall back to a more compatible method here
  }
});
.Images {
  width: 190px;
  height: 190px;
  padding: 10px;
  object-fit: cover;
}
<img class="Images" src="https://i.imgur.com/mf5YDAy.jpg" data-src="https://i.imgur.com/mf5YDAy.jpg" data-srcset="https://i.imgur.com/mf5YDAy.jpg, https://i.imgur.com/mf5YDAy.jpg" />

0 个答案:

没有答案