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 Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay