JS Bits with Bill
JS Bits with Bill

JS Bits with Bill

Simple Lazy Loading

Simple Lazy Loading

JS Bits with Bill's photo
JS Bits with Bill

Published on Jun 23, 2021

1 min read

Typically we need to write JavaScript to handle image lazy loading, often in the form of a scroll handler or intersection observer:

  <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's an experimental feature where you can simply use loading="lazy" to achieve the same result:

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

With the loading attribute set to lazy, the browser will do all the heavy lifting and will only load the image sources once the user scrolls near the image. We don't even need to use placeholder images to keep our markup valid!

As of now, this feature is supported in Chrome, Edge, and Firefox. Come on, Safari - get with it!

Here's a video using this in action:

lazyloading TikTok


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter and TikTok

 
Share this