0

我正在尝试编写一个脚本,将 jquery cdn 脚本附加到文档的正文中。

function addJquery() {
    url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.body.appendChild(script);
}
addJquery();

我在这里做错了什么

4

2 回答 2

4

您不能将脚本添加到正文并让它们执行。延迟加载的脚本必须通过head元素加载:

(function addJQuery() {
  var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
  var script = document.createElement('script');
  script.url = url;
  script.onload = function() { addJQuery(); }
  document.head.appendChild(script);
}());

但是,无论它是否已经加载,这都会加载 jQuery,所以这不好。这是您通常想要的:

(function loadMyCode() {
  // do we have jquery? if not, load it.
  if (typeof jQuery === "undefined") {
    var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
    var script = document.createElement('script');
    script.url = url;
    script.onload = function() {
       // this will run after jquery gets loaded
       loadMyCode();
    }
    document.head.appendChild(script);
    return;
  }

  // if we get here, we know we have jquery
  //
  // rest of the code goes here.
}());
于 2013-10-16T23:31:44.480 回答
0

这是另一种方式

(function () { 
var li = document.createElement('script'); 
li.type = 'text/javascript'; 
li.src= "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
li.async=true;
var s = document.getElementsByTagName('script')[0]; 
s.parentNode.insertBefore(li, s); 
})();
于 2013-10-17T02:29:19.260 回答