Search code examples
mobileresponsive-designmedia-queriesretina-display

Using screen.width and window.devicePixelRatio to detect mobile and/or retina displays is this a bad approach?


I'm developing a website for a business. It's not a web application by any stretch of the imagination but I would like it to look ok on mobile devices rather than simply scale the desktop version. After lots of research into media queries and responsive/adaptive design approaches my requirements are that the mobile layout only kicks in when the user really is on a small screen and not just resizing their desktop window, the solution is simple and can be accomplished with media queries and minimal javascript.

The approach I've come up with is something like this:

<script type="text/javascript"> 
var isRetina = window.devicePixelRatio > 1 ? true : false;
var isMobile = (screen.width < 768) ? true : false;

if (isMobile && isRetina) {
    SHOW MOBILE LAYOUT AND HI-RES IMAGES
} else if (isMobile && !isRetina) {
    SHOW MOBILE LAYOUT AND LO-RES IMAGES
} else if (!isMobile && isRetina) {
    <<SHOW HI_RES IMAGES>>
} else if (!isMobile && !isRetina) {
    SHOW DESKTOP LAYOUT AND LO-RES IMAGES
}
</script>

Before I commit to this approach I figured I'd check in and see if there is a problem or a terrible gotcha awaiting me. Or if there's an even simpler/better way to achieve this goal. I've searched a bunch on SO an haven't seen any mention of using this exact same solution.


Solution

  • The reason javascript is not a preferred method when loading CSS layouts is because javascript is usually the last thing loaded when the browser renders your page. This means that for a flash second you'll see your initial layout on the screen, before it loads the correct CSS. The simplest and most ideal approach is to make use of CSS3 Media Queries (something like this simple tutorial could go a long way: http://webdesignerwall.com/tutorials/responsive-design-in-3-steps).

    The other option you have is to use Modernizr to load your stylesheets or other files that you may want to load based on viewport sizes. Look into the Modernizr Doc, you can basically "test" for the functionalities and features on the current browser that's being used to view your webpage - and load files accordingly. As a side note, Modernizr is a JS library so again use with caution when loading CSS files - it's known to load them without the splash screen of your initial layouts but I'd still say the best practices for loading layouts based on media queries is to use the CSS3 media queries themselves.