In my application I need to load modules not at the initialization stage (by enumerating them in ./modules/modules
), but on demand later based on some condition (e.g. user authorization results). Imagine I want to provide User A with calculator module, and User B with text editor module.
Let's take boilerplatejs example app for simplicity, and assume that sampleModule1
and sampleModule2
are to be loaded on demand.
So I remove the modules from initial loading sequence in src\modules\modules.js:
return [
require('./baseModule/module'),
/*require('./sampleModule1/module'),
require('./sampleModule2/module')*/
];
and add a control to summary page (src\modules\baseModule\landingPage\view.html) to load them on-demand:
<div>
Congratulations! You are one step closer to creating your next large scale Javascript application!
</div>
<div>
<select id="ModuleLoader">
<option value="">Select module to load...</option>
<option value="./modules/sampleModule1/module">sampleModule1</option>
<option value="./modules/sampleModule2/module">sampleModule2</option>
</select>
</div>
Then I patch src\modules\baseModule\module.js to pass context to the LandingPageComponent (for some reason it doesn't in the original source code):
controller.addRoutes({
"/" : new LandingPageComponent(context)
});
and finally add the loading code to src\modules\baseModule\landingPage\component.js:
$('#ModuleLoader').on('change', function(){
require([this.value], function(mod){
moduleContext.loadChildContexts([mod]);
alert('Module enabled. Use can now use it.');
});
});
This appears to be working, but is this the best way to do it?
Does it handle context loading properly?
How to protect against loading the same module twice?