2013-10-16 38 views
0

我试图编写一个脚本,将jquery cdn脚本 附加到文档的正文。我如何创建一个脚本元素,以包括jquery

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

所有最右边j'之间'和'空间s'不会帮你 – 2013-10-16 23:27:31

+0

对不起,这是我错字。 –

回答

3

您不能添加脚本的身体,让他们执行。后期加载脚本,必须通过head元素加载:

(function addJQuery() { 
    var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"; 
    var script = document.createElement('script'); 
    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.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. 
}()); 
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); 
})(); 
+0

什么是绑定jQuery的最安全,最快和最不可能的方式。 –

+0

在你的项目目录中下载jQuery .. –

+0

我应该不使用Googles CDN,我明白这是一个最佳实践。 –

相关问题