How to render Dynamic Image as per Device
Abhinav Kumar Singh
Associate Principal Engineer | 7x Azure Certified | 4x Sitecore Certified | Sitecore Content Hub | Sitecore Search | Coveo | DevOps | Terraform
Introduction
In web development rendering image as per device view port has always been challenging and an important factor of page performance from optimization perspective. All performance testing tool suggest to use proper image format and low size images on site to increase page performance.
Solution
Now, this is no more challenge with modern HTML tag practice as per here. We can just declare picture HTML element instead of image HTML element and define properties like below and complete reference can be found here.
<picture>
<source srcset="large.png" media="(min-width: 75em)">
<source srcset="medium.png" media="(min-width: 40em)">
<img src="small.png" alt="A description of the image."
width="300" height="200" loading="lazy" decoding="async">
</picture>
Picture element also solves the problem to render different image format on different devices.
<picture
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="A description of the image."
width="300" height="200" loading="lazy" decoding="async">
</picture>>