Using properly sized images is significant for mobile websites. Adequately sized images weigh fewer kb's and therefore occupy less bandwidth on mobile devices where bandwidth may come with an additional cost.
Let's find out how we can utilize the simple HTML tag to deliver optimized images based on their size to browsers.
Deliver the properly sized image to the browser
The HTML picture element can be used to deliver the right size image based on the device screen size. With the regular <picture>
tag, all the browser sizes are served with the same sized image. The image resizing happens on the browser, reducing the use of bandwidth.
<picture>
<source media="(min-width: 600px)" srcset="banner-medium.jpg">
<source media="(min-width: 400px)" srcset="banner-small.jpg">
<img src="banner.jpg">
</picture>
In the above code, the <picture>
element contains multiple <source>
elements with their own srcset
attributes referring to different images. Depending on the browser size, the browser triggers the media query and renders the matching image. If the browser does not support the tag, the default falls back to <img>
, where all browsers support.
Different image format support
Certain image formats are optimized for the web, but not all browsers support them. For example, WebP
from google is a great way to deliver your images, but Internet Explorer doesn't support it. To overcome this, we can use the tag to deliver multiple image formats and let the browser decide what format to display.
<picture>
<source srcset="banner.webp" type="image/webp">
<img src="banner.jpg">
</picture>
With the above code, browsers that support WebP
(Chrome, Edge, Firefox, Safari, Opera) will benefit from the smaller size WebP
image. In contrast, older versions of browsers and browsers that don't support WebP
will fall back to the standard <img>
element.