How to Detect Mobile & Retina Devices: 8 Techniques

How to detect Mobile & Retina Devices: 8 Techniques
by Janeth Kent Date: 02-07-2013 web development retina mobile devices techniques


In order to serve mobile-optimized content, you need to detect which visitors are coming from mobile devices and which aren’t.

Here we have list 8 method to detect mobile browsers so you can chose the best suitable to your needs, and give your user the best experience possible.

#1 PHP User Agent

We can test the user agent comparing with a list of known mobile user agents so you can redirect the user to a different version, add a new cookie, set a global variable to be used in your CMS, set a HTML class or anything else you may want to do.

The PHP code itself is quite simple.We'll use the preg_match() function to compare current browser with an array of mobile browsers:

<?php      
//Here is the known mobile user agents list      
$mobiles = array("iPhone","iPod");        
foreach( $mobiles as $mobile ) {          
if( preg_match( "#".$mobile."#i", $_SERVER['HTTP_USER_AGENT'] ) ) {              
//Ok, this is a mobile browser, let's redirect it!              
header('Location:http://mobile.mysite.com/');               
exit();         
}}  
?>

You can disable this test, via Cookie setting a link to yoursite?nomobile=1 then you can test this var before doing the redirection part:

<?php      
//let's check if we have a get or post or cookie set to nomobile      
if ( isset( $_REQUEST['nomobile'] ) && true == $_REQUEST['nomobile'] ) {          
//now we check if we have set the cookie, so we don't need the "get" in the URL all the time          
if ( ! isset($_COOKIE['nomobile']) ) {              
setcookie("nomobile", 1, (time()+60*60*24*30) );          
}
} else {          
//nevermind, let's check if current browser is a mobile            
//Here is the known mobile user agents list          
$mobiles = array("iPhone","iPod");            
foreach( $mobiles as $mobile ) {              
if( preg_match( "#".$mobile."#i", $_SERVER['HTTP_USER_AGENT'] ) ) {                  
//Ok, this is a mobile browser, let's redirect it!                  
header('Location:http://mobile.mysite.com/');                  
 exit();              
}          
}      
}  
?>

#2 JavaScript User Agent

The JS is more suitable for places where you have little or no control on the server side code, or you want to do something specific (like a landing page).

Moreover, the JS code is quite limited because you need to load the entire site before doing the redirection.

So, here is an example:

<script type="text/javascript">      
var mobiles = array["iPhone", "iPod"];//mobile devices      
var i;        for(i=0;i< mobiles.lenght;i++){         
 //testing if the RE matches the mobile agents          
var er = new RegExp(mobiles,"i");          
if( er.test( navigation.userAgent ) ) {              
window.location = "http://mobile.mysite.com/" ;          
}}  
</script>

#3 WordPress code

WordPress actually has an internal mobile sniffing tool so you’ll have a global variable to tell you if the current user is an iPhone or not (and a few other browsers).

Here is an example:

<?php      
function load_my_styles() {          
global $is_iphone; //loading global var here          
if( $is_iphone ) {              
wp_enqueue_style( 'iphone-style', get_stylesheet_directory_uri() . '/ iphone-style.css');          
} else {              
wp_enqueue_style('normal-style', get_stylesheet_directory_uri() . '/ style.css');         
 }  
 }     
 add_action( "wp_enqueue_scripts", "load_my_styles" );  
?>

#4 WordPress Plugins

Here are some options: 

 

 

 

#5 HTML Code for Retina

This is a simple way to be done in your

, while you’re calling your styles:

<link rel="stylesheet" type="text/css" src="css/common_style.css" />  
<link rel="stylesheet" type="text/css" src="css/retina.css" media="only screen and (-webkit-min-device-pixel-ratio:2)" />

#6 Media queries

The media queries allow you to conditionally apply styles.

/* Smartphones (portrait and landscape) ----------- */  
@media only screen   and (min-device-width : 320px)   
and (max-device-width : 480px) {  /* Styles */  }    /*
Smartphones (landscape) ----------- */  
@media only screen   and 
(min-width : 321px) {  /* Styles */  }   
 /* Smartphones (portrait) ----------- */ 
@media only screen   and (max-width : 320px)
 {  /* Styles */  }    
/* iPads (portrait and landscape) ----------- */  
@media only screen   and (min-device-width : 768px)  
 and (max-device-width : 1024px) {  /* Styles */  }   
 /* iPads (landscape) ----------- */  
@media only screen   and (min-device-width : 768px)   
and (max-device-width : 1024px)   and (orientation : landscape) {  /* Styles */  }    
/* iPads (portrait) ----------- */  
@media only screen   and (min-device-width : 768px)   
and (max-device-width : 1024px)   and (orientation : portrait) {  /* Styles */  }    
/* Desktops and laptops ----------- */  @media only screen   and (min-width : 1224px) {  /* Styles */  }   
 /* Large screens ----------- */  
@media only screen   and (min-width : 1824px) {  /* Styles */  } 
/* iPhone 4 ----------- */  @media  only screen and (-webkit-min-device-pixel-ratio : 1.5),  
only screen and (min-device-pixel-ratio : 1.5) {  /* Styles */  }

If you want to target only retina devices you can try:

@media only screen and (-webkit-min-device-pixel-ratio:2){  }

#7 Media Queries via JavaScript

An obscure technique perhaps...

You can test media queries using JavaScript, and if returns true, for example, you could conditionally change classes, change image src attributes, redirect your page.

<script type="text/javascript">      
//JS version for the retina query      
var modern_media_query = window.matchMedia( "screen and (-webkit-min-device-pixel-ratio:2)");        
if( modern_media_query.matches ){          
//DO ALL THE THINGS HERE      }  
</script>

#8 Htaccess code

The idea is similar to the first PHP method.

RewriteCond %{HTTP_USER_AGENT} “ipod|iphone|ipad|blackberry”[NC]  
RewriteCond %{REQUEST_URI} ^/$  
RewriteRule ^ http://m.yoursite.com%{REQUEST_URI} [R,L]

 

 
by Janeth Kent Date: 02-07-2013 web development retina mobile devices techniques hits : 7680  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

The easiest way to align items using flexbox

With the release of flexbox in CSS, it has become an essential tool when placing elements next to each other, since, by default, the children of a display: flexare stacked…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

How To Add Filter Effects to Images with CSS

To achieve interesting effects on your images, learn about the 'filter' and 'Backdrop-Filter' properties of CSS. CSS filters are a very attractive feature of CSS that allows you to apply certain…

Why You Should Hire Node.js Developer for Your Backend Development

When developers are building a new website, they mainly focus on both frontend and backend development. The frontend code helps create the interfaces through which the app interacts with the…

Introduction to REGEX - Regular Expression

Today we are going to write about Regular Expressions known as regex or shortened  regexp, a very useful concept of using search patterns. Surely you were in a situation when you…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

How to write our own Privacy Policy

In this article we will talk about Privacy Policy statements, how you can write one and implement it on your page. Why did it pop up? These days when we browse on…

How to securely access the Dark Web in 15 steps. Second part

Let's continue with the 2nd part of our article in which we try to give you some advice on how to safely and securely explore the dark web. Let's restart from…

How to securely access the Dark Web in 15 steps. First part

The dark web can be a pretty dangerous place if you don't take the right precautions. You can stay relatively safe with a good antivirus and a decent VPN. However,…

How to Browse the Internet Anonymously: 6 tips

Most of the actions you take online are not as private as you might imagine. Nowadays, countless people and groups try to follow our online behaviour as closely as possible. Our…

How to setup an Android TV with androidtv.com/setup or the Google application

Android TVs and players are a good investment if you want to have all the entertainment at your fingertips. However, they require an installation that, although simple, has several ways…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertising related to your preferences. By clicking on "Understood" YOU AGREE TO THE USE OF THESE COOKIES. You can also SET OR DISCONTINUE the installation of cookies by clicking on "Settings" or "Reject".


Understood Reject Settings More Info