Retina images with «img srcset»


Handling High-DPI or Retina™ images is probably one of the more discussed topics in the front-end community today. The reason for this might be that front-end developers are working with technologies that hasn't quite caught up with the progress in this particular part of device technologies.

To give you an idea of what I'm talking about; A lot of mobile devices have High-DPI displays, first and most notably was the iPhone 4 which Apple used to coin the term Retina™. This kind of display have a 2x pixel density (vertically and horizontally), which means that there are 4 pixels for every one point.

The challenge

For developers and designers this pixel doubling means that artwork like images will need to be double the size it should be displayed at (horizontally and vertically). This in by itself is quite easy to fix, you just set the width and the heigh of the image in the «img» tag and then refer to an image twice the area of the defined width and height. The problem that brings is that non-retina devices, which often has less available memory will need to download a file which is double of the needed size and hence consumes much more memory and bandwidth than a normal image would. The real solution is to serve high-DPI images only to those device which can support them.

My approach

For my demo-site I'm using the W3C srcset attribute to handle High-DPI images. This allows you to set multiple sources for one image and at the same time maintain backwards compatibility with older browsers since older browsers will simply ignore the «srcset» attribute. You define it like so:

img src="normal-image.jpg" srcset="retina-image.jpg 2x"

Notice the "2x" part of the «srcset» URL. This is where you define the resolution of the image. The «srcset» attribute can take multiple comma separated image values with different parameters. If you need to display different images for different screen sizes and so on you could set multiple images here. For my demo-site I'm only using the 2x option and specifying only one alternative image.

Browser support and polyfilling

At the time of writing this only WebKit Nightly builds and Chromium supports the «srcset» attribute, but the good news is that it is coming. However, we need a solution now, hence enter the polyfill.

There are a several complete polyfills for «srcset», but they implement the whole spesification and I was really just looking for the 2x part, so I decided to create my own simple polyfill.

As you can see this is a tiny script. In short it tests if «srcset» isn't supported and whether the «devicePixelRatio» is more than one. If so, it scoops up all the images with a «srcset» attribute and swaps the image source for the one in the «srcset» attribute.

Note that this script assumes that all you want is 2x images, it is not a complete «srcset» polyfill!

So that is how I handle Hi-DPI or Retina™ images in my test-site, feel free to use it if you need it.