How to load Images faster in a Web Page | HTML

Loading Images faster in a Web Page

Tips & Tricks for loading web pages faster for best performance, great user experience and decrease the unnecessary load on web server with HTML5 changes

Loading images is the slowest loading source in a web page, perhaps. There are two basic reasons:

  1. Web pages contains many <img/> tags i.e. all images start loading simultaneously
  2. Unnessary bandwidth usage due to loading large images instead of appropriate image

Loading images simultaneously

Consider a page with 20 images, or technically say that having 20 <img> tags, they start downloading the images as per their src (source attribute) from the server. This obvious that all the images are not visible to the visitor but they are visible with the scrolling down, in more than 99.9% cases.

<img src="/favicon.jpg" loading="lazy"/>

The HTML5 attribute loading is the solution to this problem. With the loading attribute of img tag allows to use the value lazy to load the image once the user is near to reach the image.

Advantage of loading="lazy"

loading="lazy" allows to downlaod the images when they are required. In fact, some visitors do not scroll down the web apge to the end of the page and close the tab or press tha back button. This cuts down the extra load from the server, results the better performance by utilizingthe resources for other web requests and responses.

Appropriate images size

Let the browser/device resolution decide this with <picture> tag (introduced in HTML5).

<picture> <source media="(min-width:1200px)" srcset="large-photo.jpg"> <source media="(min-width:600px)" srcset="medium-photo.jpg"> <source media="(min-width:400px)" srcset="small-photo.jpg"> <img loading="lazy" src="/tiny-photo.jpg" /> </picture>

The code loads the appropriate image as per the dimensions of the device/browser. media attribtue decide which source to be loaded for the user. If none satasfied, then the src in the img will be downloaed

Summary

  1. Use loading="lazy" in img tag
  2. Use picture tag instead of img tag to downlaod image appropriate with dimensions
  3. An ideal image display should look like the following html code for best performance and the great User Expereince of the web page. <picture> <source media="(min-width:1200px)" srcset="large-photo.jpg"> <source media="(min-width:600px)" srcset="medium-photo.jpg"> <source media="(min-width:400px)" srcset="small-photo.jpg"> <img loading="lazy" src="/tiny-photo.jpg" alt="the photo" /> </picture>