Test retina image utility

Demonstrates technique for identifying and supplying assets to a retina display.

HTML

<body class="foobar">
    <img id="testImage" src="foobar.png" />
    <div id="testElement"></div>
</body>

CSS

#testElement {
    background-image: url(/path-to-image.jpg);
}

.retina #testElement {
    background-image: url(/path-to-image2x.jpg);    
}

JavaScript

var forceRetina = true;

(function (doc, forceRetina) {

    var opts = {
        find: /(.+)(\.\w{3,4})$/,
        replace: '$12x$2',
        retinaClass: 'retina'
    };

    var isRetina = function () {
        return window.devicePixelRatio > 1;
    };

    var swapImagesForRetina = function () {

        var image,
            images = doc.getElementsByTagName('img'),
            i = images.length;

        while (image = images[--i]) {
            image2x = image.src.replace(opts.find, opts.replace);
            image.src = image2x;
        }
    };

    var addRetinaToBody = function () {
        var body = doc.getElementsByTagName('body')[0],
            classes = body.className.split(' ');
        if (classes.indexOf(opts.retinaClass) == -1) {
            classes.push(opts.retinaClass);
            body.className = classes.join(' ');
        }
    };

    window.onload = function () {
        if (forceRetina || isRetina()) {
            addRetinaToBody();
            swapImagesForRetina();
        }
    };

})(document, forceRetina);
        
var tests = [
    
    function () {
        if (!document.getElementById('testImage').src.test(/2x\.png$/)) {
            return 'failed setting image class';
        }
    },
    
    function () {
        var style = window.getComputedStyle(document.getElementById('testElement'));
        if (!style.backgroundImage.test(/2x.jpg\b/)) {
            return 'failed setting background image';
        }
    },
    
    function () {
        if (!document.getElementsByTagName('body')[0].className.test(/\bretina\b/)) {
            return 'failed setting body class';
        }
    }
];

window.onload();

while (test = tests.pop()) {
    if (typeof(result = test()) != 'undefined') {
        console.log('test failed: ' + result);            
    }
}