I am building a website that I want to use jQuery Mobile to do the javascript when on mobile devices, but since jQuery开发者_如何学编程 Mobile is not supported by all desktop browsers yet I want normal jQuery to be attached. How would I do this?
Here is one way of doing it on the client:
<html>
<head>
<script type="text/javascript">
function isMobileDevice() {
var index = navigator.appVersion.indexOf("Mobile");
return (index > -1);
}
function loadJQuery() {
if(isMobileDevice())
document.write("<script type='text/javacript src='"+path_to_mobile_jquery+"'></script>");
else
document.write("<script type='text/javacript src='"+path_to_normal_jquery+"'></script>");
}
</script>
</head>
<body onload="loadJQuery();">
<!-- Content -->
</body>
</html>
Perhaps build up an enum of probable browser types and then test against window.navigator.userAgent
? You can use a library like Modernizr to test for features, but this won't get you the actual browser type. There is no (yet) userAgent prop to identify browser class (desktop, tablet, mobile, etc.), so you're stuck doing a dumb UA comparison.
Projects like 51 Degrees aim to simplify this evaluation, but they incur hidden costs--namely, 51 Degrees takes upwards of 10 seconds to evaluate the client browser and redirect accordingly. Of course, in your case, you want conditional styling--not redirect. This suggests that a window.navigator.userAgent
check might lend itself to an if(true) document.write('<javascript resource />')
type approach.
You'll have to test the browser request header (User-Agent) on the server and then bind the framework accordingly:
e.g. see http://pgl.yoyo.org/http/browser-headers.php User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18
精彩评论