Skip to content

Instantly share code, notes, and snippets.

@ronnyhaase
Last active December 15, 2015 10:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronnyhaase/5245308 to your computer and use it in GitHub Desktop.
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) !
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;
}
@ronnyhaase
Copy link
Author

Since I couldn't find a 100% satisfying solution with all possibilities/fallbacks I made one myself. Enjoy!
Feedback welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment