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

Likes(1)

Comment list count 0 Comments

No Comments

WeChat Self-Service

WeChat Consult

TaoBao

support@elephdev.com

发表
评论
Go
Top