tdc
tdc

Reputation: 5464

jQuery - fire AJAX callback after script has been loaded AND executed?

I'm running into an issue where I need to AJAX load some scripts, and only once the scripts have been both loaded and parsed/executed, should the callback function should fire.

It appears that ajax requests will fire the callback as soon as the script is downloaded, but not necessarily when it's been executed. Is there a way to do this other than mucking around with Timeouts and such?

        $.ajax({
            dataType: 'script',
            cache: false,
            async: false,
            url: 'http://example.com/script1.js'
        }).success(function () {
            // I need this callback to fire only once the script has been executed
        });

Upvotes: 1

Views: 1588

Answers (1)

Lars Anundskås
Lars Anundskås

Reputation: 1355

Your should look in to jquerys when

Will allow you to execute code after multiple async (ajax) methods are done executing.

From the jquery documentation:

Description: Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

https://api.jquery.com/jquery.when/

as for the scripts to execute before running code, jquery has a solution for this; getScripts

$.getScript("jquery.cookie.js")
    .done(function() {
        jQuery.cookie("cookie_name", "value", { expires: 7 });
});

Load multiple scripts and execute them before running your code by combining getScript and when

$.when(
    $.getScript( "/script1.js" ),
    $.getScript( "/script2.js" ),
    $.Deferred(function( deferred ){
        $( deferred.resolve );
    })
).done(function(){

    // your code

});

Another approach:

var scripts = ['script1.js','script2.js','script3.js'];
$.getScript(scripts, function(data, textStatus) {
    //do something after all scripts have loaded
});

Ref: http://www.sitepoint.com/getscript-mutiple-scripts/

Upvotes: 1

Related Questions