Lazy loading images

Lazy Loading Images

Lazy loading images is a technique that allows website owners to improve page load time and overall user experience by loading images only when they are needed or viewed by the user. This technique is especially useful for websites that have a lot of images, as it reduces the initial load time of the page and improves performance.

How it Works

The lazy loading technique works by initially loading only the images that are visible in the user's viewport, or the portion of the page that is visible on their screen. As the user scrolls down the page and new images come into view, those images are loaded as needed.

To implement lazy loading, website owners can use JavaScript to detect when an image is within the user's viewport and then load it. There are also several third-party JavaScript libraries available that can make implementing lazy loading easier.

Benefits of Lazy Loading

  • Improves page load time
  • Reduces server load and bandwidth usage
  • Decreases bounce rate by improving user experience
  • Improves SEO by reducing page load time

Code Example


// Using vanilla JavaScript
var lazyImages = document.querySelectorAll('img.lazy');

function lazyLoad() {
  lazyImages.forEach(function(img) {
    if (img.getBoundingClientRect().top <= window.innerHeight && img.getBoundingClientRect().bottom >= 0 && getComputedStyle(img).display !== 'none') {
      img.src = img.dataset.src;
      img.classList.remove('lazy');
    }
  });
}

document.addEventListener('DOMContentLoaded', lazyLoad);
document.addEventListener('scroll', lazyLoad);
document.addEventListener('resize', lazyLoad);

In the code example above, we first select all the images on the page that have the class "lazy". We then create a function called "lazyLoad" that checks if an image is within the user's viewport and loads it if it is. We also remove the "lazy" class from the image so that it is not loaded again in the future.

We then add event listeners to the document for "DOMContentLoaded", "scroll", and "resize" that call the "lazyLoad" function when triggered.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe