WebKit now supports the
srcset attribute on image (
img) elements (official specification from the W3C). This allows you, the developer, to specify higher-quality images for your users who have high-resolution displays, without penalizing the users who don’t. Importantly, it also provides a graceful fallback for browsers that don’t yet support the feature.
As you may know, WebKit has supported the
-webkit-image-set solved this by allowing you to write one simple rule and have the browser do the work of deciding which image to use and therefore which to download. (Hmmm… maybe -webkit-image-set deserves its own blog post! )
srcset attribute on
img is very similar to
-webkit-image-set. In fact, you can think of it as the markup equivalent to the CSS feature. Like the list of candidate images in
-webkit-image-set, you add a new attribute
srcset to your image elements. It’s designed to be backwards compatible: browsers that don’t support the attribute ignore it, and continue to use the
src value. Meanwhile, browser engines such as WebKit can look at the
srcset and decide which image best suits your user’s device. In most cases you won’t need anything more than this:
<img src="normal-image.jpg" srcset="better-image.jpg 2x">
Notice the “2x” after “better-image.jpg”? That tells the browser that if you’re on a display with two or more device pixels per CSS pixel, it should use “better-image.jpg” instead of “normal-image.jpg”. And if you’re not on a high-resolution display, the browser will fall back to the value specified in
src. You can also specify another candidate for 1x displays in
srcset (as shown in the example).
You can read more about
srcset in the official specification. Note that at the moment WebKit only supports the resolution modifiers (e.g. 1x, 2x, 3x). As with any new feature in WebKit there may be bugs, so please be on the lookout for anything that doesn’t behave as expected. In particular, you should verify that WebKit is downloading the minimal resources for a page, because that’s one of the goals of this feature.