【问题标题】:Choosing which JS file to load does not load file选择加载哪个JS文件不会加载文件
【发布时间】:2011-06-13 14:13:57
【问题描述】:

我有一个使用 JQuery Mobile 的移动应用程序。由于黑莓的问题,我需要在页面加载时选择要加载的 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 的同一个 &lt;script&gt; 标记中执行此操作吗?还是会导致问题?

【问题讨论】:

    标签: javascript jquery html css jquery-mobile


    【解决方案1】:

    您需要以某种方式将生成的脚本元素附加到页面。

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

    【讨论】:

      【解决方案2】:

      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
      });
      

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-18
        相关资源
        最近更新 更多