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 开发者_StackOverflowdoing this or have any suggestions of improving this script. This script does work, it just feels dirty.
Brian Cray answer seems to be false.
The right way to do this in javascript is:
var retina = window.devicePixelRatio && window.devicePixelRatio >= 2;
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.
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.
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;
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.
- Place your image inside a <noscript> tag
- Detect if you require high res images(as per Simon's answer above) read the contents of the img src inside the noscript tag and modify the path to the higher res image accordingly.
- Remove the <noscript> tag.
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
精彩评论