Search code examples
javascriptjqueryonloadjquery-on

External JavaScript with jQuery dependence being loaded before jQuery


Externally loading a script, but my script was placed by the client above jQuery (which is a requirement), as such, my script does not work.

I am trying to make my code wait until jQuery has loaded before executing, but I am having difficulty with nested functions within my code; specifically $(x).hover, or $(x).click etc.

I can separate my functions without much trouble, which include jQuery selectors (but they won't be called unless 'x y or z' is done (i.e. until after jQuery is loaded).

I don't know how to have the hover, click etc implemented as they don't work within my $(document).ready(function(){... which is located within the onload yourFunctionName described below - with thanks to user @chaos

Link to onload hook: https://stackoverflow.com/a/807997/1173155

and a quote of the above link:

if(window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function() {
            curronload();
            yourFunctionName();
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}

Thanks in advance for any help with this.


I have also looked into a loop that checks if jQuery is activated before continueing, but did not implement it as I found that JavaScript does not have a sufficient sleep method that sleeps that specific script.


Solution

  • Solution:

    if(typeof jQuery === "undefined"){
        if(window.attachEvent) {
            window.attachEvent('onload', myLoadFunction);
        } else {
            if(window.onload) {
                var curronload = window.onload;
                var newonload = function() {
                    curronload();
                    myLoadFunction();
                };
                window.onload = newonload;
            } else {
                window.onload = myLoadFunction;
            }
        }
    }
    else {
    myLoadFunction();
    }