January 25, 2022

Tutorials

Efficient Responsive Image Loading

Load time and responsive design usually impact user experience significantly, loading images with different sizes based on viewport width is a good way to solve the problem of loading unnecessarily large images in smaller screens.

there are multiple ways to load images based on screen size but HTML supports this natively with the picture tag and srcset attribute.

an extremely useful and easy solution for this problem is using the picture tag instead of img:

<!-- loading one image for all screen sizes -->

<img src="images/banner.jpg" />

<!-- loading image based on screen size -->


<picture>
  <source media="(max-width:720px)" srcset="images/banner_720.jpg">
  <img src="banner.jpg" alt="Banner">
</picture>

here if the screen with is 720px or less the smaller image will be loaded instead of the default images, we use img for the default image to have a fallback if the browser doesn’t support the picture tag (which is very unlikely) note that there can be multiple source elements for different sizes.