[英]Detect and append jQuery if not loaded with pure Javascript and a fallback
Does anybody know a way to detect if the jQuery library was loaded and if not append it and start a script as a fallback solution after it's loaded to the DOM? 有没有人知道一种方法来检测jQuery库是否已加载,如果没有附加它并在将脚本加载到DOM后启动脚本作为后备解决方案?
Here's my script: 这是我的脚本:
if (typeof jQuery == 'undefined') {
// if jQuery Library is not loaded
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
document.body.appendChild(script);
startScript();
} else {
// cool, jQuery Library is loaded
startScript();
}
function startScript() {
$.noConflict();
jQuery(document).ready(function($){
.... // my jquery code
});
}
Of course, above appends jQuery correctly but doesn't do anything because the script starts immidiately after appending. 当然,上面正确添加jQuery但没有做任何事情,因为脚本在追加后立即开始。 Any hint on this?
有什么暗示吗?
I appreciate any answer. 我很感激任何答案。 Thanks!
谢谢!
You're fine except, as you said, that you can't call startScript
immediately after appending the new script
element. 你没问题,正如你所说的那样,你不能在追加新的
script
元素后立即调用startScript
。 Instead, do a setTimeout
loop: 相反,执行
setTimeout
循环:
// ...
document.body.appendChild(script);
maybeStart();
Where maybeStart
looks like this (not within the body of the if
, function declarations aren't valid there): maybeStart
看起来像这样(不在if
的主体内,函数声明在那里无效):
function maybeStart() {
if (typeof jQuery === "undefined") {
setTimeout(maybeStart, 100);
}
else {
startScript();
}
}
That checks if jQuery is loaded and, if not, waits a 10th of a second and checks again. 检查是否加载了jQuery,如果没有,则等待10秒钟再次检查。 When jQuery is found, it calls your
startScript
. 找到jQuery后,它会调用你的
startScript
。
You might want to put a time limit in there (in case jQuery never loads, so you don't loop forever). 你可能想在那里设置一个时间限制(如果jQuery永远不会加载,所以你不要永远循环)。
Alternately, you can hook a "load"-style event on the script
element, but the mechanics of it vary from browser to browser. 或者,您可以在
script
元素上挂钩“加载”式事件,但它的机制因浏览器而异。 On some browsers it's just load
as with, say, an img
element; 在某些浏览器上,它只是
load
,例如,一个img
元素; on IE (at least older versions), you have to use readystatechange
, and on some versions of IE both work. 在IE上(至少是旧版本),你必须使用
readystatechange
,并且在某些版本的IE上都可以使用。 So you have to keep a flag so you know whether you've fired off your script, etc., and...well, the above is less complicated in the case where you know the script creates a well-known global symbol (as is the case with jQuery). 所以你必须保留一个标志,以便你知道你是否已经解雇了你的脚本等等......而且,在你知道脚本创建一个众所周知的全局符号的情况下,上面的内容就不那么复杂了(如是jQuery的情况)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.