I’ve been trying a way to detect a device’s DPI for mobile design. While I haven’t yet, I did at least find a way to detect whether the user is using a retina display. So without ado, here’s how:
var retina = window.devicePixelRatio > 1 ? true : false;
Now the variable retina will be set to true if the user has a retina display. A simple if statement can be used anywhere to execute code based on the user’s display.
if (retina) { // the user has a retina display } else { // the user has a non-retina display }
Why?
A good is example is if I have a 100×100 image (or video), the above code will tell me to upscale the image to 200×200 for it to look crisp on an iPhone 4 without forcing all users to unnecessarily download a 200×200 image. Especially given bandwidth is a major concern for mobile users.
if (retina) { var html = '<img src="my-high-res-image.jpg">'; } else { var html = '<img src="my-low-res-image.jpg">'; }
Published May 5, 2011. Tagged: javascript, mobile. Read it later with Instapaper