Is it possible to implement module loading as a promise?

I created a one-page application in which users can create reports. Users are provided with a form that allows them to select a data source, chart type and topic, then after confirmation the page downloads the required files and draws a chart.

To improve performance, I would like to load code modules and data in parallel. For example, if a user selects Pie Chart, Blue Theme, and Airline Statistics:

WHEN (the js module loads the pie chart) and (the blue css theme is loaded) and (the Airline json statistics are loading)

THEN (chart)

I found several libraries that implement AMD, and a number of libraries that implement promises, but none where module loading and promises cannot be combined, as in my example above. Is this possible, and are there libraries that already implement this?

My need for client side JavaScript.

+4
source share
2 answers

jQuery can really do this through promises . It is just a matter of changing the code.

Assuming that you own code and all living things in the same domain or in the case of a cross-domain, the server allows CORS , we will load each .ajax() . Then we will use .when() to detect when all promises are loaded and .then() to add our callback to execute all promises.

 //you can provide a detailed setting for each using .ajax() second parameter //however, jQuery can "smart detect" the content 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 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 }); 
+1
source

CommonJS modules themselves are promises, as each factory will be called only after the requirements are defined.

Therefore, if you define your data as a module, and your code as a module requiring "js", "css", "data", then this will work right out of the box.

Alternatively, you use promises as an abstraction on top of CommonJS / AMD, load CSS (e.g. LABJS?) And load data (via xhr / jsonp).

+1
source

Source: https://habr.com/ru/post/1444025/


All Articles