javascript 页面中部分脚本执行完毕回调

javascript callback when some scripts in the page have executed

我正在尝试向 HTML 页面添加加载模式,同时某些 javascript 正在执行。我的问题是我无法注意到这些脚本何时完成执行。

我试过:

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

但正如 getScript JQuery documentation 所说:

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

有没有办法为此类事件设置回调?

您可以尝试使用 $.ajax 加载脚本。

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

async 需要为 false,以便它在 运行 成功函数之前首先加载并执行脚本。