Responsive Images (srcset) and Sitecore Media

In this current age of web development more and more sites are going responsive. I mean its not a surprise really with the almost endless amount of web ready devices out there.

Thinking in terms of performance we don't want poor Eric on his 320px wide Android downloading images designed for a desktop experience. This is where responsive images, the 'srcset' and 'sizes' attributes come in handy.

Specifying srcset and sizes allows the browser to determine which size image to use. We don't need to get involved at all - the browser does it all.

For example:

<img src="dave.jpg" alt="daves face" 
  srcset="dave-320.jpg 160w, dave-320.jpg 320w, dave-640.jpg 640w, dave-1280.jpg 1280w">

Using responsive images Eric only needs to download the 320px wide image to see my face rather than waiting an eternity for the 1280px full resolution version.

Browser support is pretty good too: http://caniuse.com/#feat=srcset

...and polyfills are available for those pesky older browsers: https://scottjehl.github.io/picturefill/

What about Sitecore?

Well as we know Sitecore has a pretty neat way of handling media - if you specify a ?mw= querystring you can request a lower res version of the original image.

/medialibrary/dave.ashx?mw=320

This means I don't need to crop four images in Photoshop and upload all four to my web server to achieve the example above - I just upload dave-1280.jpg to Sitecore and write my img tag thus:

<img src="dave.jpg" alt="daves face" 
  srcset="/medialibrary/dave.ashx?mw=320 160w, /medialibrary/dave.ashx?mw=320 320w, /medialibrary/dave.ashx?mw=640 640w, /medialibrary/dave.ashx?mw=1280 1280w">

Sitecore does the rest - it will serve the image at the correct resolutions and store them in media cache too!

Great!

p.s Learn more about srcset here: http://blog.cloudfour.com/responsive-images-101-part-4-srcset-width-descriptors/

p.p.s Don't use srcset without sizes: http://blog.cloudfour.com/responsive-images-101-part-5-sizes/

Dave Leigh

Web, and long time Sitecore developer based in Bristol, UK, working at Valtech - valtech.co.uk - @valtech.
I occasionally do other things too.