DEV Community

Swislok-Dev
Swislok-Dev

Posted on

Lazy Load Images

Lazy loading is a performance booster for any site that will render images.

Why Lazy Load?

The page upon arriving will begin to render all assets including every image on a page. If a page has too many photos, this will increase the time which users to the site will be able to see them.

Lazy loading is a technique to load images only when they are about to enter the viewport which gives several benefits.

Site Performance

With image loading being delayed, this will decrease the amount of the page that will need to be downloaded on initial page load. For images that are on the landing page and within the view, these images will get loaded first and be faster.

Bandwidth

Having a site hosted on Heroku or Netlify will have only a limited amount of bandwidth available, and lazy loading will help decrease the amount of bandwidth needed to load the page.

Load Images Lazily

A way of loading images can be done using HTML and JavaScript to change the <img src=""> from blank to information. The src gets read by the browser upon load and will be delayed with JavaScript by changing the src to what the image source will be.

Start with some basic image tag in HTML:

<img class="lazy-loading-image" data-src="./assets/some-image1.jpg" />
<img class="lazy-loading-image" data-src="./assets/some-image1.jpg" />
<img class="lazy-loading-image" data-src="./assets/some-image1.jpg" />
Enter fullscreen mode Exit fullscreen mode

And now the JavaScript that will act on window scroll and start lazy loading:

document.addEventListener("DOMContentLoaded", () => {
  const images = document.querySelectorAll("img.lazy-loading-image");

  let lazyTimeout;

  const lazyLoad = () => {
    if (lazyTimeout) {
      clearTimeout(lazyTimeout);
    }

    lazyTimeout = setTimeout(() => {
      let scrollTop = window.pageYOffset;
      images.forEach((img) => {
        if (img.offsetTop < (window.innerHeight + scrollTop)) {
          img.src = img.dataset.src;
          img.classList.remove("lazy-loading-image");
        }
      });

      if (images.length === 0) {
        document.removeEventListener("scroll", lazyLoad);
        window.removeEventListener("resize", lazyload);
        window.removeEventListener("orientationChange", lazyload);
      }
    }, 10);
  }

  document.addEventListener("scroll", lazyload);
  window.addEventListener("resize", lazyload);
  window.addEventListener("orientationChange", lazyload);
})
Enter fullscreen mode Exit fullscreen mode

There are plenty of third party options towards lazy loading as well, lazysizes or jQuery Lazy to name a couple.

And with that creating full pages full of images (or videos and iframes) can be loaded later rather than have the site become slowed down by unseen assets.

Top comments (0)