lazy load

 

document.addEventListener("DOMContentLoaded", function() {
  lazyLoad() // invoke while  or invoke the function after your image process logic
})

 

 

<img class="img lazy" src="loading.gif" data-src="__src" alt="" /> 

 

function lazyLoad() {
  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.classList.remove("lazy");
          lazyImageObserver.unobserve(lazyImage);
        }
      });
    });

    lazyImages.forEach(function(lazyImage) {
      lazyImageObserver.observe(lazyImage);
    });
  } else {
    // Possibly fall back to event handlers here
  }
}

 

posted @ 2023-07-11 10:56  zyip  阅读(9)  评论(0编辑  收藏  举报