Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if jQuery is running on a page (even if jQuery is /after/ the detection script)

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.

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

I though of testing

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

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.

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?)

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

Any thoughts?

like image 274
Trass Vasston Avatar asked Mar 03 '11 22:03

Trass Vasston


2 Answers

You can use window.onload. This fires after domReady, so jQuery would surely be loaded by this point.

And check for jQuery, not $. Sometimes people use jQuery with other libraries and use $ for something different.

However, IMHO, I don't think it's a big deal if jQuery gets loaded twice.

like image 38
gilly3 Avatar answered Oct 05 '22 12:10

gilly3


Given your constraints, I see only two options:

  1. Use window.load event:

    (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 happens very late in the loading cycle, though, after all images are and such loaded.

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

    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. :-)

like image 188
T.J. Crowder Avatar answered Oct 05 '22 13:10

T.J. Crowder