javascript – 是否可以将模块加载实现为承诺?

我构建了一个单页面应用程序,用户可以在其中构建报表.向用户显示一个表单,允许他们选择数据源,图表类型和主题,然后在确认页面加载所需文件并绘制图表.

为了获得更好的性能,我想并行加载代码模块和数据.例如,如果用户选择“饼图”,“蓝色主题”和“航空公司统计”:

WHEN(加载js模块饼图)
 和(蓝色主题css加载)
 和(航空公司统计json加载)

然后(绘制图表)

我发现了许多实现AMD的库,以及许多实现promises的库,但没有一个库可以组合模块加载和promises,如上例所示.这是可能的,是否有任何库已经实现了这一点?

我需要的是客户端JavaScript.

最佳答案
jQuery可以通过
promises执行此操作.这只是修改代码的问题.

假设您拥有代码并且所有直播in the same domain或者跨域,服务器allows 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

});
点赞