How to build truly responsive images

UPDATE: it looks like Scott Jehl has already beaten me to the punch, so check out his github project!

So, I was almost asleep, and this idea popped into my head. I want to write it down for two reasons:

  1. So I don’t forget it.
  2. To see if anyone else agrees, disagrees, or sees any flaws in the idea.
Basically, I think I have figured out how to make images ridiculously responsive
  1. in a syntax that is logical and 
  2. in a way that can be powered by javascript and 
  3. fails gracefully to non-javascript supporting clients
The code starts out as simple as:
<image data-alt="Some image" data-width="300px" data-height="300px"
  id="my_image" class="some_class">
  <source src="/images/high-dpi/image.jpg"
    media="screen and (-webkit-device-pixel-ratio: 2.0)" />
  <source src="/images/print-dpi/image.jpg" media="print" />
  <source src="/images/regular-dpi/image.jpg" />
  <img src="/images/regular-dpi/image.jpg" width="300"
    height="300" alt="Some image" />

With no javascript, nothing but the <img> tag is displayed, and everything is happy.

With javascript, we run a system which turns it into the following (this becomes easier if we can evaluate media queries in JS, but I’m not sure if we can do that, so I’m showing an alternate way):

  #my_image {
    background-image: url('/images/regular-dpi/image.jpg');
    background-repeat: no-repeat;
    background-size: 300px 300px;
  @media print {
    #my_image { 
      background-image: url('/images/print-dpi/image.jpg');
  @media screen and (-webkit-device-pixel-ratio: 2.0) {
    #my_image {
      background-image: url('/images/high-dpi/image.jpg');
<image data-alt="Some image" data-width="300px" data-height="300px"
  id="my_image" style="width: 300px; height: 300px;">

And now for the fun part – we can use document.getElementById(‘my_image’).style.backgroundImage to get the right image!

This means that the last and final step then turns into:

<image data-alt="Some image" data-width="300px" data-height="300px" id="my_image">
  <img style="width: 300px; height: 300px;" src="/images/high-dpi/image.jpg"
    alt="Some image" width="300" height="300" />

Which should make it happy with screen readers and other similar systems.

This approach has a few distinct advantages:

  1. It leverages existing tools for defining when to load a particular image (media queries)
  2. It provides a graceful fallback for no javascript support
  3. It (hopefully) will be relatively close to whatever is selected for moving forward in a browser integrated solution, as it fits with the patterns already established.

So that’s it. That’s my master plan. What do you think?