Usually we need to write JavaScript to handle lazy loading of images, usually in the form of a scroll handler or a cross-viewer

  <img class="lazyload" src="placeholder.jpg" data-src="pine.png">

  <script>
    document.addEventListener('scroll', () => {
      const scrollTop = window.pageYOffset;
      const lazyImages = document.querySelectorAll('.lazyload');

      lazyImages.forEach(img => {
        if (img.offsetTop <(window.innerHeight + scrollTop)) {
          img.src = img.dataset.src;
          img.classList.remove('lazyload');
        }
      });
    });
  </script>

But now there is an experimental feature, you can simply use it loading="lazy" to achieve the same result

<img src="pine.jpg" loading="lazy">

Setting the loading property to lazy, the browser will do all the heavy lifting, and will only load the image source when the user scrolls to the vicinity of the image. We don’t even need to use placeholder images to keep our markup valid

Currently, Chrome, Edge and Firefox support this feature

点赞(1)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部