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;
},Written by Phil Freo
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Gravatar
Authors
timpietrusky
6.035K
rsmarshall
1.533K
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#