A while back, I had written about the problems encountered when displaying images in responsive design. To refresh your memory, when displaying images, it is very complex to create the necessary media queries to display the optimal image for the user's viewport, usually resulting in a series of complicated media-query strings or showing sub-optimal images.

Since realising this, I have been searching for the ideal implementation and came across numerous resources, such as Google's web fundamentals polyfill (note that srcset is supported in Chrome 38 onwards so use an older browser for the below example):

http://googlesamples.github.io/web-fundamentals/samples/media/images/sizes.html

or the open-source project on GitHub:

https://github.com/weblinc/img-srcset
https://github.com/JimBobSquarePants/srcset-polyfill

So why would I want to create my own implementation? Apart from the learning experience, I wanted to create an improved performing version of the above and be able to keep this updated with the latest spec.

Note that currently this is the first release, and will be updated with further functionality, namely:

  • Updates as the viewport size is modified (currently it only loads the correct image on page load and does not update as the window is-resized)
  • Include support for high-density pixel displays, such as 'Retina' screens.
  • Remove the dependency on jQuery

Unfortunately there will be always be two requests for the image if the size will be updated. This is because in accordance with the section 4.8.1 of the HTML5 W3C spec, an <img> element must always have a src attribute-value pair. This also allows us to work inline with progressive enhancement, i.e. if a user does not have JavaScript enabled they would still view the image (albeit not the optimal one).

Disclaimer: I am relatively new to Github so please correct me where I am wrong, as your feedback would be greatly appreciated.

Enough already, where is it...

Here is a link to the Github repo: https://github.com/IncredibleWeb/srcset and a demo page: /demo/srcset/ with exaggeratedly large images.

FAQs

  • Why don't you use the srcset attribute instead of data-srcset?
    Since the srcset spec is not finalized and frequently changing, I did not want to risk that a browser update would mean that it's no longer compatabile.

 

Thank you for reading and wishing you an incredible new year