如何延迟加载图像?

时间:2020-04-28 13:44:02

标签: javascript html css

我试图找到一种方法在我的网站上延迟加载图像,因为我将拥有大量图像库,因此我不希望出现任何性能问题。我正在在线学习教程,在该教程中,他们用data-src替换了src,但这使我的链接断开了。如果我集成了lightgallery,是否可以像这样进行延迟加载?

DECLARE EXIT HANDLER FOR SQLEXCEPTION 
BEGIN 
    ROLLBACK;
    -- other logic
END;
document.addEventListener("DOMContentLoaded", function() {
  var lazyloadImages = document.querySelectorAll("img.lazy");
  var lazyloadThrottleTimeout;

  function lazyload() {
    if (lazyloadThrottleTimeout) {
      clearTimeout(lazyloadThrottleTimeout);
    }

    lazyloadThrottleTimeout = setTimeout(function() {
      var scrollTop = window.pageYOffset;
      lazyloadImages.forEach(function(img) {
        if (img.offsetTop < (window.innerHeight + scrollTop)) {
          img.src = img.dataset.src;
          img.classList.remove('lazy');
        }
      });
      if (lazyloadImages.length == 0) {
        document.removeEventListener("scroll", lazyload);
        window.removeEventListener("resize", lazyload);
        window.removeEventListener("orientationChange", lazyload);
      }
    }, 20);
  }

  document.addEventListener("scroll", lazyload);
  window.addEventListener("resize", lazyload);
  window.addEventListener("orientationChange", lazyload);
});

1 个答案:

答案 0 :(得分:0)

如何使用CSS从DOM隐藏未加载的图像?

img.lazy {
    display: none;
}