Reputation: 3
There is a code (modules module1, module2 and module3 are loaded at the same time):
define(['module1', 'module2', 'module3'], function (module1, module2, module3) {
return { /* ... */ };
});
There is another one (module1 and module2 are loaded one after another and module3 is loaded on demand, dynamically):
define(function (require) {
var module1 = require('module1');
var module2 = require('module2');
return {
loadModule3: function () {
var module3 = require('module3');
}
};
});
How one can combine these two approaches and make modules 1 and 2 to load at the same time as in the first example, and module3 to load dynamically as in the second example (but not creating additional modules)?
Upvotes: 0
Views: 112
Reputation: 3678
The second example doesn't work as you imagine it to. The define(function(require) { ... })
syntax is just a syntactic sugar that is essentially converted to the asynchronous call similar to the first example, loading all three required modules in parallel, before the module function is executed.
If you really intend to enforce loading order you would go something like this:
define(function (require) {
// these two modules will be loaded in parallel
var module1 = require("module1");
var module2 = require("module2");
return {
loadModule3: function () {
// this module will be loaded "on-demand", when `loadModule3` is called
require(["module3"], function(module3) {
// here modules 1,2 and 3 are available
});
}
};
});
Please note, that what you call "on-demand" loading will ensure that the "module3" is available inside the callback function, the code paths relying on module3 being available should start there.
Upvotes: 1