使用常规 javascript 检测 Jquery,如果不存在则动态加载它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10728089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect Jquery with regular javascript, if not present load it dynamcally
提问by Patriotec
I need the code to use regular javascript to detect whether or not JQuery is present, if not, load JQuery file from google or another website
我需要使用常规 javascript 来检测 JQuery 是否存在的代码,如果不存在,则从谷歌或其他网站加载 JQuery 文件
UPDATE Two Working Solutions (just copying and pasting the working code here):
更新两个工作解决方案(只需在此处复制和粘贴工作代码):
From Claudio Redi
克劳迪奥·雷迪
window.jQuery || document.write("<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'>\x3C/script>")
From Rob Darwin
来自罗伯·达尔文
var jQueryScriptOutputted = false;
function initJQuery() {
if (typeof(jQuery) == 'undefined') {
if (! jQueryScriptOutputted) {
jQueryScriptOutputted = true;
document.write("<scr" + "ipt type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></scr" + "ipt>");
}
setTimeout("initJQuery()", 50);
}
}
initJQuery();
采纳答案by Rob Darwin
Something like thisshould work.
像这样的事情应该有效。
EDIT: Code added from above link.
编辑:从上面的链接添加的代码。
var jQueryScriptOutputted = false;
function initJQuery() {
//if the jQuery object isn't available
if (typeof(jQuery) == 'undefined') {
if (! jQueryScriptOutputted) {
//only output the script once..
jQueryScriptOutputted = true;
//output the script (load it from google api)
document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></scr" + "ipt>");
}
setTimeout("initJQuery()", 50);
} else {
$(function() {
//do anything that needs to be done on document.ready
});
}
}
initJQuery();
回答by Claudio Redi
There are many ways, I like this most only because is the less verbose
有很多方法,我最喜欢这个只是因为它不那么冗长
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>window.jQuery ||
document.write("<script src='js/jquery-1.7.2.min.js'>\x3C/script>")
</script>
回答by Alnitak
The niceway to load jQuery without using document.write
is:
不使用加载 jQuery的好方法document.write
是:
if (window.jQuery === undefined) {
var s = document.createElement('script');
s.src = "//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js";
document.head.appendChild(s);
}
This will cause an asynchronous load, though - so you may want to include a .onload
handler to allow execution to wait until the load has finished.
但是,这将导致异步加载 - 因此您可能希望包含一个.onload
处理程序以允许执行等待加载完成。