A few days ago, Chrome announced support for the srcset attribute through the release of Chrome 34 on their beta channel. So, why is that so important?
First let me introduce the srcset attribute. The srcset attribute, which is a proposed attribute for the <img /> element, allows authors to provide a set of images to handle graphical displays of varying dimensions and pixel densities. When authors of websites care so much about the resolution and the presentation of images, they can know use the attribute to create adaptive experiences so that the browser knows which image to serve based on the resolution of the client.
So how does the srcset attribute solve the adaptive image problem? Let’s take a look at the syntax:
First we set the src attribute as we’d normally do, and we add a comma separated list of URLs which represent the other image candidates. The 1x means “maximum pixel density of 1 device pixels per CSS pixel”. We can also specify height or width constraints such as:
Here “100w” means “maximum viewport width of 100 CSS pixels”,
The user agent now determines the most appropriate image based on the viewport resolution and the pixel density. The user agent replaces the original image data on the fly.
The srcset attribute looks more cryptic but much more powerful than the <picture /> element with its native support for the <img /> tag and density of the images. The <picture /> element only accounts for the device width.
At the time of writing, viewport width isn’t supported by the current versions of Safari, Chrome or firefox. You can also check this github repository where the srcset browser support is updated.
How can I use it today?
By simply googling for a polyfill for the srcset attribute, you will get a few examples and libraries that you can use such as this one.
Where to go from here?
You might want to look at the specifications to learn more about the usefulness of the srcset attribute and the different options that you have for the image candidates.
Code not for today, code for the future !