Skip to content Skip to sidebar Skip to footer

What Are Best Practices For Detecting Pixel Ratio/density?

I am currently using JavaScript for mobile device detection on my website, this then allows me to serve different content for mobile or desktop users. Currently I use window.device

Solution 1:

You should leverage the manufacturer's hint via the <meta name="viewport" content="width=device-width"/> or @-ms-viewport {width:device-width} feature. It basically exposes the default zoom the device manufacturer considers optimal given the pixel density of the screen. After you do that, when you call window.innerWidth it will give you what your original equation was intended for but without relying on a measurement of pixel density.

Avoid relying on window.devicePixelRatio for anything. Its meaning and the value it returns is currently in a state of flux and anything you make right now based around it will most likely break very soon.

Note: Meta viewport only works on Android, iOS, and Windows Phone 8. @-ms-viewport only works (properly) on IE10 Metro and can interfere with proper Meta viewport behavior on Windows Phone 8.

Solution 2:

There is a Generic Solution to get device Pixel Ratio

Next code uses window.devicePixelRatio as a starting point BUT also has a fallback based on window.matchMedia() Web API.

The browser support for both those features is almost perfect, so this should work great for most of use cases.

Here is a function that retrieves this information, originally written by PatrickJS and published as a GitHub Gist:

functiongetDevicePixelRatio() {
    var mediaQuery;
    var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
    if (window.devicePixelRatio !== undefined && !is_firefox) {
        returnwindow.devicePixelRatio;
    } elseif (window.matchMedia) {
        mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\
          (min--moz-device-pixel-ratio: 1.5),\
          (-o-min-device-pixel-ratio: 3/2),\
          (min-resolution: 1.5dppx)";
        if (window.matchMedia(mediaQuery).matches) {
            return1.5;
        }
        mediaQuery = "(-webkit-min-device-pixel-ratio: 2),\
          (min--moz-device-pixel-ratio: 2),\
          (-o-min-device-pixel-ratio: 2/1),\
          (min-resolution: 2dppx)";
        if (window.matchMedia(mediaQuery).matches) {
            return2;
        }
        mediaQuery = "(-webkit-min-device-pixel-ratio: 0.75),\
          (min--moz-device-pixel-ratio: 0.75),\
          (-o-min-device-pixel-ratio: 3/4),\
          (min-resolution: 0.75dppx)";
        if (window.matchMedia(mediaQuery).matches) {
            return0.7;
        }
    } else {
        return1;
    }
}

Useful links: MDN - window.devicePixelRatio, MDN - Window.matchMedia()

CanIUse: window.devicePixelRatio, Window.matchMedia()

Post a Comment for "What Are Best Practices For Detecting Pixel Ratio/density?"