DEV Community

Cover image for Simple Lazy Loading
JS Bits Bill
JS Bits Bill

Posted on • Edited on

2

Simple Lazy Loading

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>
Enter fullscreen mode Exit fullscreen mode

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">
Enter fullscreen mode Exit fullscreen mode

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay