[英]Choosing which JS file to load does not load file
我有一個使用 JQuery Mobile 的移動應用程序。 由於 blackberry 的問題,我需要在頁面加載時選擇要加載的 JS 文件。 我在 html 頁面上執行此操作,如下所示:
<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>
我打了兩個alert()
調用,但文件從未加載(我也簽入了 firebug)。 我在這里做錯了什么嗎?
我也想為 css 這樣做。 我知道這樣做我必須這樣做:
loadcss = document.createElement('link');
loadcss.setAttribute("rel", "stylesheet");
loadcss.setAttribute("type", "text/css");
loadcss.setAttribute("href", cssfile);
document.getElementsByTagName("head")[0].appendChild(loadcss);
我可以在加載 JS 的同一個<script>
標記中執行此操作嗎? 還是會引起問題?
您需要以某種方式將生成的腳本元素 append 到頁面。
var head = document.getElementsByTagName('head')[0];
head.appendChild(ourJSFile);
head.appendChild(fileref);
Blackberry 檢查永遠不會運行。
if (navigator.userAgent == 'BlackBerry') {
...是無效的。 試試這個:
if(/blackberry/i.test(navigator.userAgent) {
// ...rest of your blackberry code here...
此外,由於您使用的是 jQuery,因此您也可以輕松加載腳本。
$.getScript('my-script.js', function() {
// optional callback function on success
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.