Tuesday, July 31, 2012

Detect Retina Display using Javascript

New retina display macbook pro asks web developers to detect retina display using Javascript, so that web server can serve high resolution images for better visual experience on retina display. Today I did some quick test on different browsers and found Safari/Chrome already supports retina display though Chrome doesn't provide window.retina interface to Javascript developers. I believe Firefox will soon add this support in such a browser war.

Firefox 14.0.1
window.retina => undefined
window.devicePixelRatio => undefined

Chrome 21.0.1180.57
window.devicePixelRatio => 2
window.retina => undefined

Safari 6.0 (8536.25)
window.retina => true
window.devicePixelRatio => 2

Based on above experimental result, I suggest to use below Javascript to detect retina display and do corresponding logic (like loading high resolution images). See pseudo codes below.

var retina = (window.retina || window.devicePixelRatio > 1);
if (retina) {
//retina display
//load high resolution picture
$(img).src = 'high-res.jpg';
else {
//non-retina display
//load low resolution picture
$(img).src = 'high-res.jpg';

1 comment:

  1. I will try on my site.... I think it's a good solution. Thanks