如何确定jQuery是否在页面上运行(即使jQuery是/ after /检测脚本) [英] How to determine if jQuery is running on a page (even if jQuery is /after/ the detection script)

查看:74
本文介绍了如何确定jQuery是否在页面上运行(即使jQuery是/ after /检测脚本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个可以嵌入像youtube视频这样的页面中的do-dad。我想要的特殊效果需要jQuery才能工作。

I'm working on a do-dad that can be embedded in a page like a youtube video. The particular effect I want needs jQuery to work.

我想加载jQuery,条件是页面上的内容还没有添加jQuery。

I want to load jQuery on the condition that something on the page hasn't already added jQuery.

我虽然在测试

if (typeof($)=='function'){...

但这只适用于加载jQuery的情况。在页面到达我的脚本时运行。既然最近的最佳做法是将脚本嵌入到页脚中,我的嵌入代码可能永远不会在大多数时间看到jQuery。

but that only works if jQuery is loaded & running by the time the page gets to my script. Since best practices these days is to embed you scripts in the footer, my embed code probably will never see jQuery most of the time anyway.

我想做测试 onready 而不是 onload ,但 onready 函数在jQuery的。 (我想我可以使用一个独立的脚本?有一个好的吗?)

I thought of doing the test onready instead of onload, but the onready function is inside of jQuery. (I suppose I could use a standalone script? is there a good one?)

最后,我虽然在超时延迟后测试了jQuery,但这似乎不太优雅最好的和不可靠的。

Lastly, I though of testing for jQuery after a timeout delay, but this seems inelegant at best and unreliable at worst.

有什么想法吗?

推荐答案

鉴于你的约束,我只看到两个选项:

Given your constraints, I see only two options:


  1. 使用 window.load 事件:

(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 发生非常在加载周期的后期,在所有图像都被加载之后。

window.load happens very late in the loading cycle, though, after all images are and such loaded.

使用超时。好消息是超时可能很短。

Use a timeout. The good news is that the timeout can probably be quite short.

(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)
        }
    }
})();

您必须调整以确定计数器和间隔的最佳值。但是如果即使在第一个或第二个循环中也没有加载jQuery,我的猜测(未经测试)是它不会被加载...除非别人正在做你正在做的事情。 : - )

You'll have to tune to decide the best values for the counter and the interval. But if jQuery isn't loaded even on the first or second loop, my guess (untested) is that it isn't going to be loaded...unless someone else is doing what you're doing. :-)

这篇关于如何确定jQuery是否在页面上运行(即使jQuery是/ after /检测脚本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆