Javascript 如果尚未加载 jQuery,如何加载它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6813114/
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
How can I load jQuery if it is not already loaded?
提问by Jeff
I have a initializor.jsthat contains the following:
我有一个包含以下内容的initializor.js:
if(typeof jQuery=='undefined')
{
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
headTag.appendChild(jqTag);
}
I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isn't, adds it to the Head tag.
然后我将该文件包含在另一页的某处。该代码检查 jQuery 是否已加载,如果未加载,则将其添加到 Head 标记中。
However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said:
但是,jQuery 没有初始化,因为在我的主文档中,我声明了一些事件来测试它。我也尝试在支票下面写一些 jQuery 代码,Firebug 说:
"jQuery is undefined".
“jQuery 未定义”。
Is there a way to do this? Firebug shows the jquery inclusion tag within the head tag!
有没有办法做到这一点?Firebug 在 head 标签中显示 jquery 包含标签!
Also, can I dynamically add code into the $(document).ready()
event? Or wouldn't it be necessary just to add some Click events to a few elements?
另外,我可以动态地将代码添加到$(document).ready()
事件中吗?或者是否有必要仅向一些元素添加一些 Click 事件?
回答by Adam Heath
jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>
). You would have to add an onload listener to the script (jqTag
) to detect when it loads and then run your code.
jQuery 无法立即使用,因为您正在异步加载它(通过将其附加到<head>
)。您必须向脚本 ( jqTag
)添加一个 onload 侦听器以检测它何时加载然后运行您的代码。
e.g.
例如
function myJQueryCode() {
//Do stuff with jQuery
}
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
jqTag.onload = myJQueryCode;
headTag.appendChild(jqTag);
} else {
myJQueryCode();
}
回答by beardhatcode
To include jQuery you should use this:
要包含 jQuery,你应该使用这个:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js">\x3C/script>')</script>
it uses the Google CDNbut provides a fallback an has a protocol relative URL.
它使用Google CDN,但提供了一个后备方案,并有一个协议相对 URL。
Note: Be sure to change the version number to the latest version
注意:请务必将版本号更改为最新版本
if window.jQuery
is defined, it will not continue to read the line since it is an or that already contains a true value, if not it wil (document.)write the value
see: theHTML5Boilerplate
如果window.jQuery
定义了,它不会继续读取该行,因为它是一个或已经包含一个真值,如果不是,它将(文档)写入该值,
请参阅:theHTML5Boilerplate
also: you forgot the quotes, if jQuery is not defined:
另外:如果未定义 jQuery,您忘记了引号:
typeof window.jQuery === "undefined" //true
typeof window.jQuery == undefined //false ,this is wrong
you could also:
你也可以:
window.jQuery === undefined //true
回答by aljgom
If you're in an async function, you could use await
like this:
如果你在一个异步函数中,你可以这样使用await
:
if(!window.jQuery){
let script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
}
/* Your jQuery code here */
If you're not, you can use (async function(){/*all the code*/})()
to wrap and run all the code inside one
如果不是,您可以使用(async function(){/*all the code*/})()
将所有代码包装并运行在一个
.
.
Alternatively, refactoring Adam Heath's answer(this is more readable IMO). Bottom line, you need to run the jQuery code AFTER jQuery finished loading.
或者,重构Adam Heath 的答案(这是 IMO 更具可读性)。最重要的是,您需要在 jQuery 完成加载后运行 jQuery 代码。
jQueryCode = function(){
// your jQuery code
}
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
Or you could also wrap it in a function to change the order of the code
或者你也可以把它包装在一个函数中来改变代码的顺序
function runWithJQuery(jQueryCode){
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
}
runWithJQuery(function jQueryCode(){
// your jQuery code
})
回答by Steve Elliott
The YepNope loader can be used to conditionally load scripts, has quite a nice, easy to read syntax, they have an example of just this on their website.
YepNope 加载器可用于有条件地加载脚本,它的语法非常好,易于阅读,他们的网站上有一个示例。
You can get it from their website.
你可以从他们的网站上得到它。
Example taken from their website:
取自他们网站的示例:
yepnope([{
load: 'http:/-/ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
complete: function () {
if (!window.jQuery) {
yepnope('local/jquery.min.js');
}
}
}
回答by Fatih Hayrio?lu
This site code is solved my problem.
这个站点代码解决了我的问题。
function loadjQuery(url, success){
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
head.appendChild(script);
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
}
if (typeof jQuery == 'undefined'){
loadjQuery('http://code.jquery.com/jquery-1.10.2.min.js', function() {
// Write your jQuery Code
});
} else {
// jQuery was already loaded
// Write your jQuery Code
}
http://99webtools.com/blog/load-jquery-if-not-already-loaded/
http://99webtools.com/blog/load-jquery-if-not-already-loaded/
回答by Ivijan Stefan Stipi?
This is old post but I create one workable solution tested on various places.
这是旧帖子,但我创建了一个在不同地方测试过的可行解决方案。
<script type="text/javascript">
(function(url, position, callback){
// default values
url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
position = position || 0;
// Check is jQuery exists
if (!window.jQuery) {
// Initialize <head>
var head = document.getElementsByTagName('head')[0];
// Create <script> element
var script = document.createElement("script");
// Append URL
script.src = url;
// Append type
script.type = 'text/javascript';
// Append script to <head>
head.appendChild(script);
// Move script on proper position
head.insertBefore(script,head.childNodes[position]);
script.onload = function(){
if(typeof callback == 'function') {
callback(jQuery);
}
};
} else {
if(typeof callback == 'function') {
callback(jQuery);
}
}
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){
console.log($);
}));
</script>
Explanation you can find HERE.
你可以在这里找到解释。