I’m currently trying to edit a website for a client which uses Adobe Contribute so it uses a different stylesheet if the user is browsing from a mobile phone. The mobile phone stylesheet is much simpler and strips out background images and styles to reduce load time. I understand it would be better practice to have a completely seperate website for the mobile, but this is not practical for the client as he needs to be able to update his websites content using Contribute.
This is working in some devices already such as the iPhone (last time I tested!) but on my Android phone I have a strange problem. When I visit the URL or click on a link, it displays the website using the default stylesheet. If I refresh the page it then decides to show the site rendered with the mobile stylesheet. It is almost as though the UserAgent is not being picked up by my code until I click refresh.
Here is the code I am using:
<link href="css/style.css" id="stylesheet" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var userAgent = navigator.userAgent;
if(userAgent.search("Mobile")>=0) document.getElementById("stylesheet").href = "css/style_mob.css";
if(userAgent.search("Nokia")>=0) document.getElementById("stylesheet").href = "css/style_mob.css";
if(userAgent.search("SymbianOS")>=0) document.getElementById("stylesheet").href = "css/style_mob.css";
</script>
The script only shows for a few devices but you get the general idea.
My User Agent string is as follows:
Mozilla/5.0 (Linux; U; Android
2.1-update1; en-gb; T-Mobile_G2_Touch Build/ERE27) AppleWebKit/530.17
(KHTML, like Gecko) Version/4.0 Mobile
Safari/530.17
EDIT:
I should add that I have tried to use media queries but this does not work at all on either the iPhone or Android. The code above works a treat on the iPhone. Below is the code I am using when trying to have this work with media queries.
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link href="../css/style.css" id="stylesheet" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" media="only screen and (max-width: 480px), only screen and (max-device-width: 480px)" href="../css/style_mob.css" />
Can´t you use media queries to determine what stylesheet the browser must use? Checking for individual user agents seems the wrong way to go about it.
Edit: I just noticed the media queries code you are using and I noticed you are using a different path:
css/style_mob.csswhen using the javascript and../css/style_mob.css. Is that a typo or could it be the reason it’s not working?