Last active
December 15, 2015 10:19
-
-
Save ronnyhaase/5245308 to your computer and use it in GitHub Desktop.
JavaScript function that tests for "Retina" screen (pixel ratio > 1.92).
Note that there are also high-resolution devices that not necessarily fit (pixel ratio > 1 < 2) !
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isRetina() { | |
// | |
// The easy way, a handy little property in the global scope | |
// | |
if ( 'devicePixelRatio' in window ) | |
return window.devicePixelRatio >= 1.92; | |
// | |
// The hard way, via Media Queries | |
// | |
// All possible media queries | |
var mqs = [ | |
'only screen and (-webkit-min-device-pixel-ratio: 2)' /* WebKit */ | |
, 'only screen and ( min--moz-device-pixel-ratio: 2)' /* Firefox < v16 */ | |
, 'only screen and ( -o-min-device-pixel-ratio: 2/1)' /* Opera */ | |
, 'only screen and ( min-device-pixel-ratio: 2)' /* Cross browser */ | |
, 'only screen and ( min-resolution: 192dpi)' /* Newer & better cross-browser */ | |
, 'only screen and ( min-resolution: 2dppx)' /* Best */ | |
]; | |
// Reference to matchMedia function, also consider Paul Irish's matchMedia polyfill (https://github.com/paulirish/matchMedia.js) here, for legacy browsers | |
var mediaQuery = window.matchMedia || window.msMatchMedia; | |
// no matchMedia function there :( , return undefined since we can't tell if it's a Retina screen | |
if ( mediaQuery === undefined ) | |
return undefined; | |
// Iterate our media queries and execute them, return true on a match | |
for (var i = 0, len = mqs.length; i !== len; i++) | |
if ( mediaQuery(mqs[i]).matches ) | |
return true; | |
// We had the tools, but it's no Retina screen | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since I couldn't find a 100% satisfying solution with all possibilities/fallbacks I made one myself. Enjoy!
Feedback welcome.