Search code examples
javascriptjqueryjquery-callback

javascript callback when some scripts in the page have executed


I'm trying to add a loading modal to an HTML page while some javascript are executing. My problem is that I can't get to notice when these scripts have finished executing.

I've tried with:

$.when(
    $.getScript( "/script1.js" ),
    $.getScript( "/script2.js" ),
    $.getScript( "/script3.js" ),
    $.Deferred(function( deferred ){
        $( deferred.resolve );
    })
).done(function(){
    console.log('everything have been executed!');
});

But as the getScript JQuery documentation says:

The callback is fired once the script has been loaded but not necessarily executed.

Is there a way to set a callback for such event?


Solution

  • You could try using $.ajax to load the scripts.

    $.ajax({
        async:false,
        url:'/script.js',
        type:'GET',
        data:null,
        dataType:'script',
        success:function(){
            console.log('Executed')
        }
    });
    

    async needs to be false, so that it loads and executes the script first, before running the success function.