Lazy Load Images

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 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:

 class="lazy-loading-image" data-src="./assets/some-image1.jpg" />
 class="lazy-loading-image" data-src="./assets/some-image1.jpg" />
 class="lazy-loading-image" data-src="./assets/some-image1.jpg" />

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);
})

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.

Total
1
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
asp.net:-autenticacion-oidc-multi-tenant-–-parte-2

ASP.NET: Autenticación OIDC Multi Tenant – Parte 2

Next Post
build-a-number-guessing-game-in-ruby

Build a number guessing game in Ruby

Related Posts