开发者

Choosing which JS file to load does not load file

I have a mobile app using JQuery Mobile. Because of issues with blackberry I need to choose which JS files to load when the page is loaded. I do this on the html page like so:

<html>
<head>
<!-- Code -->
<script type = "text/javascript" >
//Check if phone is a blackberry
if (navigator.userAgent == 'BlackBerry') {
    //Load blackberry workaround
    var ourJSFile = document.createElement('script');
    ourJSFile.setAttribute("type", "text/javascript");
    ourJSFile.setAttribute("src", "DefaultBBWorkaround.js");
    //Load Newest JQuery
    var fileref = document.createElement('script');
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", "http://code.jquery.com/mobile/latest/jquery.mobile.min.js");
} else {
alert("Started");
    //Load default
    var ourJSFile = document.createElement('script');
    ourJSFile.setAttribute("type", "text/javascript");
    ourJSFile.setAttribute("src", "Default.js");
    //Load last stable version of JQuery
    var fileref = document.createElement('script');
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", "jquery.mobile-1.0a4.1.js");
    alert("Done");
}
</script>
</head>
<body>
<!-- Code -->
</body>
</html>

I hit both alert() calls, but the file is never loaded (I checked in firebug as well). Is there something I am doing wrong here?

Also I want to do this for the css as well. I know to do so I would have to do this:

loadcss = document.createElement('link');
loadcss.setAttribute("rel", "stylesheet");
loadcss.setAttribute("type", "text/css");
loadcss.setAttribute("href", cssfile);
document.getElementsBy开发者_运维百科TagName("head")[0].appendChild(loadcss);

Can I do that in the same <script> tag where I load the JS? or will that cause issues?


You'll need to append the generated script element(s) to the page in some fashion.

var head = document.getElementsByTagName('head')[0];
head.appendChild(ourJSFile);
head.appendChild(fileref);


The Blackberry check is never run.

if (navigator.userAgent == 'BlackBerry') {

...is invalid. Try this instead:

if(/blackberry/i.test(navigator.userAgent) {
  // ...rest of your blackberry code here...

Also since you're using jQuery, you can easily load scripts that way as well.

$.getScript('my-script.js', function() {
  // optional callback function on success
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜