Responsive Images – Without the Cruft

"That's a lot of markup for an image." The primary concern I've heard about responsive images since I wrote my responsive images article is that they're just too verbose.

Things just got better.

Old telephones at the Museum of Communication
Responsive Images. Resize me and WEEEE!

Saving users untold kilobytes of data and speeding up their experience should be worth the cruft. But now there's an even better option: srcset + sizes.

<picture>, the element soon to be in many browsers, solves a lot of use cases. One of the big ones is "art direction", which involves, for example, choosing one image for small screens, a different image for medium screens, and a third image for large screens.

While that's a good use case, and I'm glad it's being considered, art direction is rarely an option for the sites that I'm involved with. Instead, I focus on responsive images primarily for the bandwidth savings.

And for that use case, where every image is the same except for its size, the <picture> spec now lets us get that without all of the verbosity of the picture element.

Like the original responsive images article, I'll show you how in two steps.

The script

The first step: drop an extra script into the footer of the site.

<script src="/assets/libs/picturefill/picturefill.js" async></script>

I use picturefill because it properly polyfills this. But soon, browsers will natively support this, and the script won't be necessary.

The markup

Here's the original.

<img src="" alt="Griffins. A pryde of them.">

Here's the verbose markup, using the span-based pattern of picturefill 1.0.

<span data-picture data-alt="Griffins. A pryde of them.">
    <span data-src=""></span>
    <span data-src=""  data-media="(min-width: 476px)"></span>
    <span data-src="" data-media="(min-width: 951px)"></span>
    <span data-src="" data-media="(min-width: 1426px)"></span>
    <!--[if (lt IE 9) & (!IEMobile)]>
    <span data-src=""></span>
    <!-- Fallback content for non-JS browsers. Same img src as the initial, unqualified source element. -->
        <img src="" alt="Griffins. A pryde of them.">

And here's the much more succinct markup, using srcset and sizes, supported in picturefill 2.0, which as of this writing is still in beta. The browser (or the polyfill) will figure out which image to download based on the information it has available.

<img src="" alt="Griffins. A pryde of them."
     srcset=" 475w,

Now you have no excuse.