jQuery getScript call function when script is loaded

user1121487 picture user1121487 · Jun 12, 2012 · Viewed 7.9k times · Source

Here is the script:

$("#button").click(function(){
    $.getScript('script.js', function(){
       script.init();
    });
});

I want to be able to run script.init() like the above example, but if I do it like this, I have to click the button twice to be able to get the script. -When it runs script.init() the first time, it is not loaded yet it seems.

So how can I make sure the script is loaded before I do something with it?

Answer

Arm0geddon picture Arm0geddon · Jun 12, 2012

Try this:

$(window).load(function() {
    $.getScript('script.js', function() {
        $("#button").click(function() {
           script.init();
        });
    });
});

Or, try using the jQuery.ajax function instead of the shorthand:

$("#button").click(function () {
    $.ajax({
        url: "script.js",
        dataType: "script",
        success: function () { script.init(); }
    });
});