In my application, I need to load the modules not at the initialization stage (by listing them in ./modules/modules ), but upon request later based on some condition (for example, user authorization results). Imagine that I want to provide User A with a calculator module and User B with a text editor module.
For simplicity, consider the sample templateplatejs application and assume that sampleModule1 and sampleModule2 should load on demand.
So, I remove the modules from the initial boot sequence in src \ modules \ modules.js:
return [ require('./baseModule/module'), /*require('./sampleModule1/module'), require('./sampleModule2/module')*/ ];
and add the control to the summary page (src \ modules \ baseModule \ landingPage \ view.html) to load them upon request:
<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 fix src \ modules \ baseModule \ module.js to pass the context to the LandingPageComponent object (for some reason, it is not in the source code):
controller.addRoutes({ "/" : new LandingPageComponent(context) });
and finally add the download 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 seems to work, but the best way to do it?
Does it handle context loading correctly?
How to protect against loading the same module twice?