Teddyk
Teddyk

Reputation: 143

How do I perform a callback on JQuery once it's loaded?

I'm downloading JQuery asynchronously:

function addScript(url) {
    var script = document.createElement('script');
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
}
addScript('jquery.js');

// non-jquery code ...

// jquery specific code like: $()...

As such - how do I call my JQuery specific code once JQuery is loaded (because since I'm downloading my JavaScript asynch - it's not blocking, which is good, but is trying to execute my JQuery specific code before JQuery has been loaded).

Upvotes: 4

Views: 2720

Answers (4)

For me this works (tested in FireFox 33.0.3):

    if(typeof(jQuery) == "undefined"){

        //create onload-callback function
        window["__9384nalksdfalkj04320"] = function(){
            console.log("jQuery=" + jQuery);
        };

        //load jQuery asynchronously
        var script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("onload", "__9384nalksdfalkj04320();"); //register onload-callback listener function
        script.setAttribute("src", "http://code.jquery.com/jquery-latest.min.js");
        document.head.appendChild(script);
    }

Upvotes: 2

Chris Moschini
Chris Moschini

Reputation: 37947

You can inline LabJs into your page (potentially, every page). On the downside, you're inlining a script over and over. On the upside, LabJs is pretty small - 4k minified - and it lets you handle complex asynchrony load patterns cross-browser with very simple code like:

<script>
// Minified LabJs goes here
</script>
<script>
function init() {
    // Your code after jquery loads goes here
}

$LAB
.script('//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
.wait(init);
</script>
</body>

Upvotes: 1

Tomas
Tomas

Reputation: 5143

You can host a copy of the jquery file yourself. Then you can add a call to the callback function at the bottom of jquery.js:

/* jquery code goes here ... */

my_onload_callback();

Upvotes: 4

dclowd9901
dclowd9901

Reputation: 6826

I'm not much on standard Javascript, but you may try doing something like this:

var script_object = new addScript('jquery.js');

script_object.onLoad('addScript("my_jquery_related.js")');

Admittedly, that's a mega shot in the dark.

If that doesn't work, maybe pass through your function as a callback variable in your JS loader:

addScript(url, function(){ function_to_call();})

function addScript(url, call_back_function) {
    var script = document.createElement('script');
    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);

    call_back_function.call;
}
addScript('jquery.js');

That's all I got :\

Upvotes: -1

Related Questions