简体   繁体   English

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

[英]How can I dynamically add external scripts using jQuery?

I thought that I could just use jQuery's .append() and add them to the head, but that doesn't seem to be working for my external scripts (Knockout.js). 我认为我可以使用jQuery的.append()并将它们添加到头部,但这似乎不适用于我的外部脚本(Knockout.js)。

Here's my code that runs when the page loads. 这是我加载页面时运行的代码。 It seems to be working for the stylesheet, but not for the external scripts. 它似乎适用于样式表,但不适用于外部脚本。

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 [...]
        });
    }

Here's my test environment where you can see my current code in action with Firebug. 这是我的测试环境,您可以在其中查看我当前使用Firebug执行的代码。

Here's what I'm seeing in Firebug after the page loads: 这是我在页面加载后在Firebug中看到的内容:

在此输入图像描述

EDIT: It looks like it's having issues with the Knockout.js scripts in my code, so I'll look into those. 编辑:在我的代码中看起来它与Knockout.js脚本有问题,所以我会研究那些。 Thank you for the comments and answer regarding dynamic scripts. 感谢您关于动态脚本的评论和答案。 I learned something :) 我学到了东西:)

Have you tried jQuery.getScript() ? 你试过jQuery.getScript()吗? It basically loads a script from the server and then executes it. 它基本上从服务器加载一个脚本然后执行它。

 $.getScript("yourScript.js", function(){});

Try to add scripts this way, I have seen that issue before in some browsers. 尝试以这种方式添加脚本,我之前在某些浏览器中看到过这个问题。

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = script_url;
$("head").append( script ); 

According to this jQuery API pages comment here , this behavior is perfectly normal, as jQuery cleans up the DOM after you 根据这个jQuery API页面注释 ,这种行为是完全正常的,因为jQuery会在你之后清理DOM

Your code is executed (if URL is correct, and XSS is not blocked) whether you fetch it by $.append() ing it or use $.getScript() . 您的代码是执行的(如果URL正确,并且XSS未被阻止),无论您是通过$.append()获取它还是使用$.getScript()

However, loading your site gives me at least three two solid errors. 但是,加载您的网站至少会给我 三个 错误。 You might want to work on those. 您可能想要处理这些问题。

The errors: 错误:

ReferenceError: $ is not defined
search.js
Line 54

and

TypeError: jQuery is undefined
http://knockoutjs.com/js/jquery.tmpl.js?_=1353351345859
Line 7

You should use something like AngularJS if your application is this complex. 如果你的应用程序很复杂,你应该使用像AngularJS这样的东西。 Otherwise you are reinventing the wheel. 否则你正在重新发明轮子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM