Just-in-Time Retina

We want our images to shine in their natural retina glory, but on mobile and non-retina screens this might be overkill; there’s no sense loading a large image that will end up the size of a postage stamp. We also don’t want to load duplicates (or triplicates) of every image and switch between them as necessary, when it would be far easier (and better) to only load what we need, when we need it, and no more. Just what we’re looking for .

var $images=$("img[data-1x]");
if (window.devicePixelRatio == 2) {
    $.each($images, function() {
        var $this=$(this);
        $this.attr("src", $this.data("2x"));
    });
} else {
    $.each($images, function() {
        var $this=$(this);
        $this.attr("src", $this.data("1x"));
    });
}

This is a handy bit of code, but it does rely on the following custom attributes to be added to any image that you want to swap out dynamically:

<img src=""
     data-1x="/images/photo.jpg"
     data-2x="/images/photo@2x.jpg">

Efficient coding is all about trade offs, and the more non-standard markup we add to our code, the bulkier it becomes and the more chances there are for errors. Wouldn’t it be nice if we only had to set one attribute rather than two? Given that we’re adding our images via Markdown, we will have to add a custom attribute — like so {: data-src='/support/photo.jpg'} — directly after the source declaration, so keeping it down to one attribute would limit distraction in a file that is supposed to be uncluttered and human-readable.

var images = $("img");
$.each(images, function() {
    var img  = $(this),
        path = img.attr("data-src"),
        src  = path.split(".");
    if (window.devicePixelRatio == 2) {
        img.attr("src", src[0]+"@2x."+src[1]);
    } else {
        img.attr("src", src[0]+"."+src[1]);
    }
});

The function is roughly the same length and compensates for the lack of a second declaration by pulling apart the source and inserting the retina modifier before the suffix. Obviously, this is not as flexible as setting the specification on a per image basis, but it does save us some clutter in our Markdown.

This still leaves us with a minor issue to resolve since our code will not pass validation with an empty ‘src’ attribute hanging about. We could solve that with a light-weight 1x1 pixel spacer image, but that would mean additional HTTP requests at ~4kb a pop. That’s not much, but we can do better. The Tiniest GIF Ever to the rescue!

Now we only load the images we need, when we need them, and our code passes validation without too much extra overhead.