Corey
Corey

Reputation: 5818

iPhone4 retina display detection with PHP and/or JavaScript

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

Answers (5)

Simon Rolin
Simon Rolin

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

James Westgate
James Westgate

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.

  1. Place your image inside a <noscript> tag
  2. 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.
  3. 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

Upvotes: 0

Kent Brewster
Kent Brewster

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

Matthew Sielski
Matthew Sielski

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

Daniel
Daniel

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

Related Questions