How to make script execution wait until jquery is loaded

Late to the party, and similar to Briguy37’s question, but for future reference I use the following method and pass in the functions I want to defer until jQuery is loaded:

function defer(method) {
    if (window.jQuery) {
        method();
    } else {
        setTimeout(function() { defer(method) }, 50);
    }
}

It will recursively call the defer method every 50ms until window.jQuery exists at which time it exits and calls method()

An example with an anonymous function:

defer(function () {
    alert("jQuery is now loaded");
});

Leave a Comment