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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay