Mobile Detection JavaScript

mobile digg

If your objective is to have a mobile website, apart from different facts, you need to know about how to turn your site into a mobile friendly one (mobile sites usually differ very much from “normal” sites, regarding content, quantity and design). There’s also something really important to be considered: Installing the Mobile Detection JavaScript.

How does it work?

In plain words, when somebody enters your site from a mobile device, this script executes itself recognizing that the user’s browser is in a mobile device and automatically redirects the user to the mobile site.

The JavaScript code includes one-for-all matching for various user agents so it uses less space, which is something extremely important, because the code is downloaded to a mobile device, and the lighter, the better. The JavaScript identifies iPhone, iPod, iPad, Blackberry, Palm, Android devices, Windows Compact Edition and any agent that includes “mobile” (as iPad does).

The used regular expression is not case-sensitive. That means that no matter if the browser reports with lower, capital, or mixed cases. If it is an iPhone, the code will be identified.

How can we make the site to redirect us every time we access it?

The user’s browser history will not record a new “entry” if we use location.replace instead of location.href. And this script does it. This means the user will not be able to go “back” to get the script executed again and get redirected again. It works as if the mobile site was the one the user visited right from the start. If clearer for the user, the better.

This technique is not infallible. Browsers can also unauthorize JavaScript execution and the code would not be working. However, is rare this happens because 2.0 webs works on its major part on JavaScript, even for mobile devices. On the other hand, if we consider this situation, it implies changes that are not very simple.

There are lots of variances for this script, a simple google search will lead you to hundreds of them.

So, if you are planning to have a mobile friendly site, please, make sure it has this script!

You can copy the script from here, remember to replace “http://landing.getcs.com/pca/mlanding.html” with the URL of your mobile friendly site, and it should work:

<script type="text/javascript">
	if (navigator.userAgent.match(/(iphone|ipod|blackberry|android|palm|windows\s+ce|mobile)/i))
	{ location.replace("http://landing.getcs.com/pca/mlanding.html"); }
</script>