RequireJS not waiting for module loading?

I'm struggling to download only the modules that I need. This list of modules will differ, for example, below.

This code is embedded in the dynamic page:

<script data-main="js/main" src="js/require.js"></script> <script> //APPROACH #1 (function(){ <% foreach(DashBoardItem item in AvailableItems){ %> require('js/dashboard/<%= item.Name.ToLower() %>').init(<%= CurrentUser.ID %>); <% } %> }()); </script> 

The idea is to create something like:

 <script> //APPROACH #1 (function(){ require('js/dashboard/sales').init(123); require('js/dashboard/inventory').init(123); require('js/dashboard/deadlines').init(123); }()); </script> 

I'm not sure if this is possible or ho, because the above approach is throwing an error

The module name "js / dashboard / sales" has not yet been loaded for context: _. Use require ([])

I tried to create this instead:

 <script> //APPROACH #2 require(['js/dashboard/sales', 'js/dashboard/inventory', 'js/dashboard/deadlines' ], function(sales, inventory, deadlines){ sales.init(123); inventory.init(123); deadlines.init(123); }); </script> 

But this does not succeed, because, apparently, RequireJS will not wait for the modules to load, and these three callback parameters ( sales , inventory , deadlines ) will be undefined when executed.

Am I completely wrong about this? How to transfer a variable list of required modules from the server to client JS?

UPDATE - fixed

My problem was that my modules (sales, inventory, deadlines) were incorrectly announced. Thanks to @anoopelias comment below, I realized that I used require(...) instead of define(...) in them. Therefore, they were as follows:

 //example of WRONG sales.js module require(['jquery', 'other-module'], function($, otherModule){ //do stuff, return some object instance }); 

Once I fixed it, as shown below, I could use APPROACH # 2 on top, and it worked fine.

 //example of correct sales.js module define(['jquery', 'other-module'], function($, otherModule){ //do stuff, return some object instance }); 
+6
source share
1 answer

just for the record, for approach # 1 you just forgot [] around the modules:

  <% foreach(DashBoardItem item in AvailableItems){ %> require(['js/dashboard/<%= item.Name.ToLower() %>']).init(<%= CurrentUser.ID %>); <% } %> 

if your js / main does not require these modules, requirejs will complain. Even if you include them in your js / main, you need to β€œwait” for main to finish loading (so the foreach socket requires a call to js / main)

0
source

All Articles