Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  56] [ 6]  / answers: 1 / hits: 27734  / 14 Years ago, thu, march 3, 2011, 12:00:00

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?


More From » jquery

 Answers
15

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



[#93453] Thursday, March 3, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sophiak

Total Points: 242
Total Questions: 90
Total Answers: 103

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;