It is hard to keep focus on all the different problems we are facing to deliver the best possible experience to our users. One of those is the question of "How can I use sharp images (e.g. for high-DPI devices) while not draining bandwidth for users who might not need it?"
This post is a short (but hopefully sweet) introduction to
srcset with a focus on resolution switching- a really neat way to solve this problem.
srcset is oftentimes used as an attribute for an HTML
<img> element. Its purpose is to provide a list of image sources (i.e. URLs) from which the browser can choose from based on additional information you are providing. In this post, we are going to focus on specifying the resolutions. However, please note that
srcset also supports other use cases - feel free to check them out here. Here's a short example on how you can define a list of images along with their resolutions:
<img src="image_1x.jpg" srcset=" image_1x.jpg 1x, image_2x.jpg 2x" alt="A beautiful alt description of some image" />
In simplified terms, we are basically saying: "Look browser, I have a
srcset defined -
1x resolution (basically the base),
2x the resolution" and so on. The browser can then use this information to decide which image to render.
Note: in the above example, you could also just use
image_1x.jpg, instead of
image_1x.jpg 1x, because
1x is implied. However, I personally like to specify it either way to make it more explicit.
The benefit of using this approach is that the browser will be able to determine what the user will need. Suppose the user is looking at the page using a high-DPI screen (think of Retina devices), the browser will be able to recognize it and say "Whoops, we got a nice screen with good resolution.. the
1x resolution probably won't make the cut so I'll better request and use the image defined as
The cool part is that this way, you automatically save your users bandwidth when the higher resolution image is not needed as the browser will not make a request to get it.
srcset is a very nice tool we can use to optimize our web pages even further. While I have only focused on specifying the resolution, please take a look at the other use cases you might find
srcset helpful for.
Unfortunately, there's one thing I haven't mentioned yet and that is that
srcset is not supported on IE11. If your project needs to support IE11 you will have to fall back on polyfills or other ways to achieve comparable results.
I hope you enjoyed this short post. Feel free to comment if you want to leave feedback or just want to say hello. You can also reach out to me at Twitter.