how to detect, in a cross-browser compatible way, the pixel density of the device visiting a webpage so that one can either serve standard or highres images without forcing doubled images to any device?
Is there any javascript library that automates this?
iPhone 4s, iPhone 5, iPad3, iPad4, Macbook 15", Macbook 13" all use Retina display.
Android also support high resolution display, as well as Windows 8(Lumia 920) as mentioned by @JamWaffles.
Adding high resolution support is good for user experience but it definitely add load for developer, as well as bandwidth for mobile. Somebody don't suggest doing that.(Peter-Paul Koch, see the bottom "further reading")
There are two methods to implement this function. One is Javascript and the other is CSS. All current solutions are for Retina, but could extend to Android high resolution easily.
CSS solution is about Media Query and -webkit-min-device-pixel-ratio
or -webkit-device-pixel-ratio
<img>
tagJavascript solution is about window.devicePixelRatio
property.
For normal images, say an icon
.sample-icon {
background-image: url("../images/sample-icon.png");
background-size: 36px 36px;
}
For Retina, add those below
@media only screen and (-webkit-min-device-pixel-ratio: 2), /* Webkit */
(min-resolution: 192dpi) /* Everyone else */ {
.sample-icon {
background-image: url("../images/sample-icon-highres.png");
background-size: 18px 18px;
}
You can use min-resolution: 2dppx
to replace min-resolution: 192dpi
, for those who don't want to remember numbers
Note the difference:
Resource: + http://www.w3.org/blog/CSS/2012/06/14/unprefix-webkit-device-pixel-ratio/ + http://view.jquerymobile.com/master/demos/widgets/buttons/#CustomIcons
Use window.devicePixelRatio
property to detect resolution.
if (window.devicePixelRatio >= 2) {
alert("This is a Retina screen");
//Do something to manipulate image url attribute
//for example add `@2x-` before all image urls
}
Browser Support
Safari, Android WebKit, Chrome 22+ and on Android, Opera Mobile, BlackBerry WebKit, QQ, Palm WebKit, Ref: http://www.quirksmode.org/blog/archives/2012/06/devicepixelrati.html
Android device use 1.5 as high resolution instead of 2 in Retina. http://developer.android.com/guide/webapps/targeting.html --#Targeting Device Density with CSS, #Targeting Device Density with JavaScript
http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html "I’m not a big fan of serving special retina images because it makes the web too heavy — especially over a mobile connection. Nonetheless people will do it." -- Peter-Paul Koch
Update 2013-04-18 Update jQuery mobile link
I found this:
var retina = window.devicePixelRatio > 1;
this should make retina return true, which you could use an if function to serve the right images.
Source: http://briancray.com/posts/detect-retina-displays-with-javascript
-InfiniDaZa
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With