STYLE SWITCHER

Lazy Load Images for Website Performance

Lazy loading images means loading images on websites asynchronously — that is, after the above-the-fold content is fully loaded, or even conditionally, only when they appear in the browser’s viewport. This means that if users don’t scroll all the way down, images placed at the bottom of the page won’t even be loaded.

Why Should You Care About Lazy Loading Images?

There are at least a couple of excellent reasons why you should consider lazy loading images for your website:
  • If your website uses JavaScript to display content or provide some kind of functionality to users, loading the DOM quickly becomes critical. It’s common for scripts to wait until the DOM has completely loaded before they start running. On a site with a significant number of images, lazy loading — or loading images asynchronously — could make the difference between users staying or leaving your website.
  • Since most lazy loading solutions work by loading images only if the user has scrolled to the location where images would be visible inside the viewport, those images will never be loaded if users never get to that point. This means considerable savings in bandwidth, for which most users, especially those accessing the web on mobile devices and slow-connections, will be thanking you.
<img data-src="image.jpg" alt="test image">
img {
  opacity: 1;
  transition: opacity 0.3s;
}

img[data-src] {
  opacity: 0;
}
JavaScript then adds the src attribute to each img element and gives it the value of their respective data-src attributes. Once images have finished loading, the script removes the data-src attribute from img elements altogether:
[].forEach.call(document.querySelectorAll('img[data-src]'),    function(img) {
  img.setAttribute('src', img.getAttribute('data-src'));
  img.onload = function() {
    img.removeAttribute('data-src');
  };
});
Website

Recent Article

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Keep your skills sharp, get informed.

    Subscribe to our mailing list and get interesting stuff and updates to your email inbox