Javascript 如何确定jQuery是否在页面上运行(即使jQuery在检测脚本之后运行)
我正在开发一个do-dad,它可以像youtube视频一样嵌入到页面中。我想要的特定效果需要jQuery才能发挥作用 我想在页面上还没有添加jQuery的情况下加载jQuery 我想到了测试Javascript 如何确定jQuery是否在页面上运行(即使jQuery在检测脚本之后运行),javascript,jquery,detect,Javascript,Jquery,Detect,我正在开发一个do-dad,它可以像youtube视频一样嵌入到页面中。我想要的特定效果需要jQuery才能发挥作用 我想在页面上还没有添加jQuery的情况下加载jQuery 我想到了测试 if (typeof($)=='function'){... 但只有当jQuery在页面到达我的脚本时被加载并运行时,这才有效。因为现在的最佳实践是在页脚中嵌入脚本,所以我的嵌入代码可能在大多数情况下都不会看到jQuery 我想用测试onready代替onload,但是onready函数在jQuery内部
if (typeof($)=='function'){...
但只有当jQuery在页面到达我的脚本时被加载并运行时,这才有效。因为现在的最佳实践是在页脚中嵌入脚本,所以我的嵌入代码可能在大多数情况下都不会看到jQuery
我想用测试onready
代替onload
,但是onready
函数在jQuery内部。(我想我可以使用一个独立的脚本?有好的吗?)
最后,我考虑过在超时延迟后测试jQuery,但这在最好的情况下似乎不雅观,在最坏的情况下也不可靠
有什么想法吗?考虑到您的限制,我只看到两种选择:
窗口。加载事件:
(function() {
if (window.addEventListener) {
// Standard
window.addEventListener('load', jQueryCheck, false);
}
else if (window.attachEvent) {
// Microsoft
window.attachEvent('onload', jQueryCheck);
}
function jQueryCheck() {
if (typeof jQuery === "undefined") {
// No one's loaded it; either load it or do without
}
}
})();
window.load
发生在加载周期的很晚,但是,在加载所有图像之后
(function() {
var counter = 0;
doDetect();
function doDetect() {
if (typeof jQuery !== "undefined") {
// ...jQuery has been loaded
}
else if (++counter < 5) { // 5 or whatever
setTimeout(doDetect, 10);
}
else {
// Time out (and either load it or don't)
}
}
})();
(函数(){
var计数器=0;
doDetect();
函数doDetect(){
if(jQuery的类型!=“未定义”){
//…jQuery已加载
}
如果(++计数器<5){//5或其他什么
设置超时(doDetect,10);
}
否则{
//超时(加载或不加载)
}
}
})();
您必须调整以确定计数器和间隔的最佳值。但是,如果jQuery即使在第一个或第二个循环中也没有加载,我的猜测(未经测试)是它不会被加载……除非其他人正在做你正在做的事情。:-)您可以使用
window.onload
。这会在domReady之后触发,因此jQuery肯定会在这一点加载
并检查jQuery
,而不是$
。有时,人们将jQuery与其他库一起使用,并将$
用于不同的内容
然而,恕我直言,如果jQuery被加载两次,我并不认为这有什么大不了的。我已经用这段代码做了一段时间了。在加载之前,它还会检查jQuery的最低版本(在我们的例子中,我们仍然使用1.4.2):
/* Checks if JQuery is loaded... if not, load it. */
/* Remember to update minimum version number when updating the main jquery.min.js file. */
if (typeof jQuery != 'undefined') {
/* jQuery is already loaded... verify minimum version number of 1.4.2 and reload newer if needed */
if (/1\.(0|1|2|3|4)\.(0|1)/.test(jQuery.fn.jquery) || /^1.1/.test(jQuery.fn.jquery) || /^1.2/.test(jQuery.fn.jquery)|| /^1.3/.test(jQuery.fn.jquery)) {
loadJQ();
}
} else {
loadJQ();
}
/* loads jQuery if not already loaded, or if not a recent enough version */
function loadJQ() {
/* adds a link to jQuery to the head, instead of inline, so it validates */
var headElement = document.getElementsByTagName("head")[0];
linkElement=document.createElement("script");
linkElement.src="../scripts/lib/jquery.min.js";
linkElement.type="text/javascript";
headElement.appendChild(linkElement);
}
“
如果(typeof($)=='object'){…
”,那就不应该工作了。$的类型应该是“函数”,而不是“对象”。我还应该检查jQuery
,而不是$
,以防使用noConflict
。(还请注意,typeof
是一个运算符,而不是一个函数;除非它的操作数是一个复杂的表达式,否则不需要在它的操作数周围使用parens…尽管它们没有什么害处。)@T.J.Crowder:哦,天啊,jquery是一个函数!现在更改我的帖子……他说“即使jquery是/在/检测脚本之后”.然后他在课文中继续说。这显然是他要求的重要部分。谢谢……我一定错过了那个细节。