如何使用jQuery动态添加外部脚本?

Jon*_*Jon 3 javascript jquery dynamic onload

我认为我可以使用jQuery的.append()并将它们添加到头部,但这似乎不适用于我的外部脚本(Knockout.js).

这是我加载页面时运行的代码.它似乎适用于样式表,但不适用于外部脚本.

if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.8.0') {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src",
        "http://code.jquery.com/jquery-1.8.0.min.js");
    if (script_tag.readyState) {
      script_tag.onreadystatechange = function () { // For old versions of IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') {
              scriptLoadHandler();
          }
      };
    } else {
      script_tag.onload = scriptLoadHandler;
    }
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
}

function main() { 
        jQuery(document).ready(function($) {
            $("head").append("<script type='text/javascript' src='http://knockoutjs.com/js/jquery.tmpl.js'></script>");
            $("head").append("<script type='text/javascript' src='http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js'></script>");
            $("head").append("<link href='style.css' rel='stylesheet' type='text/css' />");

            // Then it appends the necessary HTML code [...]
        });
    }
Run Code Online (Sandbox Code Playgroud)

这是我的测试环境,您可以在其中查看我当前使用Firebug执行的代码.

这是我在页面加载后在Firebug中看到的内容:

在此输入图像描述

编辑:在我的代码中看起来它与Knockout.js脚本有问题,所以我会研究那些.感谢您关于动态脚本的评论和答案.我学到了东西:)

ale*_*gui 8

你试过jQuery.getScript()吗?它基本上从服务器加载一个脚本然后执行它.

 $.getScript("yourScript.js", function(){});
Run Code Online (Sandbox Code Playgroud)