q2z2uw
Last Updated: April 07, 2016
·
5.384K
· philfreo
Philsq100

Detect HiDPI (Retina) displays in JavaScript

When you are dynamically constructing image URLs via JavaScript it can be useful to know if you need to show @2x images.

app.isRetina = function(){
    var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\
            (min--moz-device-pixel-ratio: 1.5),\
            (-o-min-device-pixel-ratio: 3/2),\
            (min-resolution: 1.5dppx)";
    if (window.devicePixelRatio > 1)
        return true;
    if (window.matchMedia && window.matchMedia(mediaQuery).matches)
        return true;
    return false;
}();

(boosted from https://github.com/imulus/retinajs/blob/master/src/retina.js)

For example, Close.io uses this to render Gravatar profile images.

getGravatar: function(size) {
    var url = this.get('image');
    if (!url) return null;
    if (app.isRetina) size = size * 2;
    return url+'?d=mm&s='+size;
},
Say Thanks
Respond