A simple srcset example

I have a simple page where I occasionally post links to web things I make. The design couldn't be much simpler: fixed width images (I know, I know) and a short description of what each thing does.

When I upgraded my main machine to a laptop with a high-DPI screen, I wrote some javascript to conditionally download high resolution images for high-DPI screens because I didn't want to see grainy images on my site. I went this route because responsive images (picture, srcset, I don't remember seeing any talk of source at the time but it was probably being discussed) were still in flux. And, AFAIK, not supported in most browsers so that would have meant I needed a polyfill.

Here we are a couple years later and responsive images are well supported. The JS worked, but, in the context of current browsers it:

  • re-implements something the browser does without JS
  • relies on JS to run before downloading any images

Both should be avoided but that second bullet is the one that really hurts– you'd always see placeholders where the images should be when visiting the page.

I re-read the Responsive Images in Practice (OK fine, read it for the first time) and this quote:

srcset if you’re lazy, picture if you’re crazy™ –Mat Marquis

summarizes where I ended up.

The new version of my page uses srcset to specify those high-res images and ditches that hacky javascript. The old markup (which inserts a src attribute derived from the id, hence the stuttering when the page loaded):
<img id="arctic-ice">

compared with the new:
<img src="images/arctic-ice.png" srcset="images/arctic-ice@2x.png 2x">

It's more verbose but the trade-off is significant when looking at page load times. With JS hack, the page was taking roughly two seconds to load. Using srcset, that's down closer to one second. Using some fuzzy math, that's a ~50% faster page load!

And here are dev tools screen shots showing the improvements:
High resolution images via JS

High resolution images vis srcset

Saved an http request, I have less JS to fiddle with and the right DPI image (and only the right DPI image) is always sent.