In the previous tip I talked about optimizing your images using the
loading attribute. Continuing with the theme, I want to talk about using a newer HTML tag called
picture to build better-optimized images.
The picture tag looks something like this:
<picture> <source srcset="..."></source> <img src="..."></img> </picture>
sourcedefines a set of optimized images to load in certain contexts
imgis our fallback, default image in case
So in a
source is our start player. It takes a special attribute called
srcset which, you guessed it, defines a list of sources for our images (almost like an array).
The syntax for
srcset is a little nuanced and I feel the MDN docs do it more justice than I can. Nonetheless, I can sum up the attribute. The idea is that we can define multiple versions of our image inside of a
picture tag and use the
srcset attribute to select a particular version depending on the screen-size.
So for example, let's say we have a background image for our hero section and we're using a
picture tag for it. On mobile, we can have a particular image be the background image. On tablet we can have another. Then, finally, we have the desktop version.
All of these three images can be defined inside the
source and all live together under one
The idea being that if we have optimized images for mobile, tablet, and desktop rather than one
img trying to fit to all, then we've improved overall performance and UX.