Detecting Retina Displays From JavaScript And CSS

I was looking at how to target Apple’s retina display for high resolution web pages earlier.

My first attempt was to look at the user agent string, but an up to date iPhone 4 sends the same string as an up to date iPhone 3GS.

A quick look around the internet reveals the solution for JavaScript is to actually use the window.devicePixelRatio property.

For a standard browser, this will be 1. However, on a retina display it will 2 – meaning twice the pixels.

For example…

if (window.devicePixelRatio >= 2) {
// retina display
} else {
// standard display
}

You can check your current devicePixelRatio using the following…

<script type="text/javascript">
document.write("Your browser has a devicePixelRatio of " + window.devicePixelRatio + "");
</script>

Apple aren’t the only ones using this in their webkit based browsers, you can read how to target device pixel density on Android. Android defines a density of 1 to be medium density, anything 1.5 or above as high density and anything under 0.75 to be low density.

On the client side we can use this to decide if we want to bring in retina quality imags, or standard ones. There is a jQuery plugin called Retina that does this.

If want to to pass display information back to the server to decide what images to render, this is a bit more complicated.

The best way to approach this would be to have a JavaScript set a cookie containing the devicePixelRadio and have the server read this back. A quick Google reveals that Ben Doran is doing just this, Detecting the iPhone4 and Resolution with Javascript or PHP.

Here’s Ben’s example code (slightly tweaked)…

<?php
if( isset($_COOKIE["pixel_ratio"]) ){
$pixel_ratio = $_COOKIE["pixel_ratio"];
if( $pixel_ratio >= 2 ){
echo "Is HiRes Device";
}else{
echo "Is NormalRes Device";
}
}else{
?>
<script type="text/javascript">
writeCookie();
function writeCookie()
{
the_cookie = document.cookie;
if( the_cookie ){
if( window.devicePixelRatio >= 2 ){
the_cookie = "pixel_ratio="+window.devicePixelRatio+";"+the_cookie;
document.cookie = the_cookie;
location = '<?=$_SERVER['PHP_SELF']?>';
}
}
}
</script>
<?php

A different approach could be to use CSS and media types. Webkit browsers like Safari on an iPhone have -webkit-min-device-pixel-ratio, Gecko browsers like Firefox have -moz-device-pixel-ratio.

An example using this approach on webkit could be

<link
rel="stylesheet"
type="text/css"
href="/css/retina.css"
media="only screen and (-webkit-min-device-pixel-ratio: 2)"
/>

One thought on “Detecting Retina Displays From JavaScript And CSS”

  1. Hello!
    I know this article may be a little out-dated and not maintained anymore, but if you use
    window.devicePixelRatio
    on a zoomed-in page with firefox, you get >1 results, thus making it inappropriate to detect mobile screens.
    Thank you!

Comments are closed.