Reputation: 5818
I'm creating a detection script that sniffs out any device (currently only iPhone4) with a retina display (or similar) when a user arrives at my site. Because the resolution is greater, I need to push higher res images/graphics. The only solution that I can find (using PHP and JavaScript) is to detect the devicePixelRatio
and set a cookie. Here is the code that I am using:
<?php
$imgPath = "images/";
if(isset($_COOKIE["imgRes"])){
$imgRes = $_COOKIE["imgRes"];
if( $imgRes >= 2 ){
$imgPath = "images/highRes/";
}
} else {
?>
<script language="javascript">
var the_cookie = "imgRes="+window.devicePixelRatio+";"+the_cookie;
document.cookie = the_cookie;
location = '<?=$_SERVER['PHP_SELF']?>';
</script>
<?php
}
?>
Has anyone come across a better method of doing this or have any suggestions of improving this script. This script does work, it just feels dirty.
Upvotes: 9
Views: 3772
Reputation: 940
Brian Cray answer seems to be false.
The right way to do this in javascript is:
var retina = window.devicePixelRatio && window.devicePixelRatio >= 2;
Upvotes: 9
Reputation: 11444
I have a technique I use which makes a single request for the correct image using script, falling back to a default when no javascript is available.
You will need a small polyfil to reliably read the contents of noscript tags across all browsers (IE8 and below) which you can find here
Upvotes: 0
Reputation: 2520
Brian Cray has a one-line JavaScript answer:
http://briancray.com/2011/05/05/detect-retina-displays-with-javascript/
It's this easy:
var retina = window.devicePixelRatio > 1 ? true : false;
Upvotes: 0
Reputation: 847
You could use CSS3 media queries like described here, but this will only let you add additional CSS rules client-side, not adjust the image path server-side. This would work well for a site with a limited number of static images.
Upvotes: 2
Reputation: 890
I implemented a very "low tech" solution when I needed to add support for retina display on a site: I doubled the size of all the images and set them to display at 50% their size.
Unfortunately, it meant every device was loading high resolution images even if it didn't support them, but I didn't have a lot of graphics to worry about, so it was a good solution for me.
Upvotes: 1