码迷,mamicode.com
首页 > 其他好文 > 详细

图片懒加载高性能实现(IntersectionObserver方法)

时间:2020-06-24 11:51:11      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:inter   ssi   event   tar   reac   entry   ade   serve   cse   

页面img标签

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

JS实现

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
  }
});

 

图片懒加载高性能实现(IntersectionObserver方法)

标签:inter   ssi   event   tar   reac   entry   ade   serve   cse   

原文地址:https://www.cnblogs.com/peter-web/p/13186765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!