Developing for high-resolution displays often requires different image resources for each image. Because of this, there’s been a need for a more standard way of serving responsive content images – ones that adapt to different resolutions and viewport sizes.
What if the browser had a way of knowing which images to load without fetching any unused resources? We can already achieve something similar with CSS using a combination of media queries for pixel density or resolution to display hi-res background images. For instance:
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { .hero { background-image: url('../img/hero-bg-2x.png'); } }
This will display hero-bg-2x.png
as a background image only when the device pixel ratio is at least 2, or the resolution is at least 192dpi.
Fortunately, the new srcset
attribute addresses our need for adaptive content images. It allows us to define high-quality images for high-resolution displays without affecting users on lower resolutions.
How srcset Works
Currently, the first implementation of srcset
only lets us define a set of images for different pixel densities using resolution modifiers. To see how it works we’ll need the latest nightly build of WebKit, as it’s the only browser that supports srcset
. This is cutting edge stuff!
Simply add the srcset
attribute to an img
element and at least one resolution modifier. The browser then displays the most appropriate image from the available options. For example, the 2x
modifier targets the image to use if the display has a pixel density of 2 or higher:
<img src="my-dog.jpg" srcset="my-dog-2x.jpg 2x">
This tells the browser that if we’re on a display with 2 or more device pixels per CSS pixel, it should use “my-dog-2x.jpg”. Meanwhile, users on lower pixel density displays will see “my-dog.jpg,” so no bandwidth will be wasted on the hi-res image.
Conclusion
Undoubtedly, srcset
has a long way to go, but it’s pressing forward in the right direction and helping us solve a problem we’ve needed solved for quite some time. Overall, this will be a more intelligent way to serve our content images.
A future implementation of srcset
will allow us to load images based on the viewport size:
<img src="dog.jpg" srcset="dog-mobile.jpg 720w, dog-tablet.jpg 1280w, dog-desktop.jpg 1x, dog-hi-res.jpg 2x" alt="Rover">
Of course, we still need to use the src
attribute for browsers that don’t support srcset
. Those browsers will simply ignore the srcset
value and gracefully fall back to src
. Although browser support for srcset
is currently our biggest hang-up, Boris Smus and James South have developed some handy polyfills we can use in the meantime.