Often there may be a requirement to redirect a user to a mobile friendly version of a website.
In many cases a responsive layout is only the first step to a ideal user experience. Due to mobile data usage restrictions, some websites will need to reduce the resource load of assets (which were created for desktop environments) by swapping to smaller, more compressed versions… OR be responsible for the wrath of a user who has exceeded their data cap because of your website.
To avoid the latter, your website should determine if a user is visiting from a mobile device and adjust accordingly.
To do so, we need to access the ‘navigator.userAgent’. The userAgent returns comprehensive information on the users browser.
you can test it on desktop by typing the following into a html document and checking your browser output window
It should return something like this
“User-agent header sent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11”
Below is a mobile usage example which will redirect users if they are using any of the listed devices.
Place the script between your opening and closing ‘head’ tags.
**NOTE: There have been many discussions on how ‘fool proof’ this method is. At the time of writing this, it was working with all major devices.
As new devices come out the userAgent data may be more cryptic. I will try to update this post if there are any changes. Test where possible.