jQuery实际上可以通过promises做到这一点。这只是修改代码的问题。
假设您拥有代码并且都生活在同一个域中,或者如果跨域,服务器允许 CORS,我们将使用.ajax()
. 然后我们将.when()
用于检测所有承诺何时加载并.then()
添加我们的回调来执行所有承诺解决。
//you can provide a detailed setting for each using .ajax()'s second parameter
//however, jQuery can "smart detect" the content's dataType
var chart = $.ajax(urlOfChart), //script
theme = $.ajax(urlOfTheme), //css
data = $.ajax(urlOfData); //JSON
//we use .when() to check when all three resolves
//the arguments will be the jqXHR objects for the requests
//in the order they were given in the argument list
$.when(chart,theme,data).then(function(chart,theme,data){
//according to jQuery.ajax(), if a script is requested, it is evaluated
//and we still get it's plain text content
//so with respect to the script, we do no processing
//with the css, we get it as plain text since no dataType value handles it
//we embed it into the DOM by creating a style element
//and append the text in it for the styles to take effect on the page
$('<style type="text/css" />').html(theme).appendTo('head');
//as for the JSON, jQuery converts it into an object
//and is passed as an argument as the return data for that promise
//...everything is now requested, retrieved and prepared...
//everything else goes under here
});