簡體   English   中英

是否有可能實現模塊加載的承諾?

[英]Is it possible to implement module load as a promise?

我已經構建了一個頁面應用程序,用戶可以在其中構建報告。 向用戶顯示一個表格,允許他們選擇數據源,圖表類型和主題,然后在確認后頁面將加載所需的文件並繪制圖表。

為了獲得更好的性能,我想並行加載代碼模塊和數據。 例如,如果用戶選擇“餅圖”,“藍色主題”和“航空公司統計信息”:

何時(已加載js模塊餅圖)和(已加載藍色主題CSS)和(已加載Airline Stats json)

THEN(繪制圖表)

我發現有許多實現AMD的庫,也有許多實現promise的庫,但是沒有一個模塊可以像上面的示例那樣將模塊加載和promises結合在一起。 這可能嗎,並且已經有任何庫實現了嗎?

我需要客戶端JavaScript。

jQuery實際上可以通過promises做到這一點。 這只是修改代碼的問題。

假設您擁有代碼,並且所有代碼都位於同一域或跨域中,則服務器允許CORS ,我們將使用.ajax()加載每個代碼。 然后,我們將使用.when()來檢測何時所有的Promise都已加載,並使用.then()添加回調以執行所有Promise的解析。

//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

});

CommonJS模塊本身就是一個承諾,因為只有定義了需求后,每個工廠才會被調用。

因此,如果您將數據定義為模塊,而將代碼定義為需要'js','css','data'的模塊,那么這實際上可以直接使用。

或者,您可以將promise作為CommonJS / AMD之上的抽象,通過(例如通過LABJS?)加載CSS,以及(通過xhr / jsonp)加載數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM