I’ve been looking at require.js and I am a bit confused on how to use it for my widgets system.
My widgets system basically allows the user to choose which widget s/he wants to see which gets stored in the database.
So when the user loads the page on the next visit, s/he will see only the widgets s/he selected. In effect only loading the html, javascript needed for the displayed widgets instead of loading all the html and javascript for all the widgets and then hidding the stuff which is not needed.
What I am confused about is how to do this with require.js
Am I supposed to dynamically generate the require.js code below? If the user has saved widget_1, widget_5 and widget_70, I am assuming I need to dynamically generating javascript like so?
require(['widget_1','widget_5','widget_70'], function(w1, w5, w70){
// then do something here?
});
the require line, is that supposed to be dynamically generated based on an sql query?
So if they only select a single widget to save for next time viewing, they will only get:
require(['widget_90'], function(w90){
// then do something here?
});
Is that what I am supposed to be doing?
Always define path’s to the libraries that your modules rely on too often, something like below:
File: scripts/main.js
Note: You need to include libraries with-in a module and return as an object, something like below:
File: lib/jquery.1.7.2.js
Same approach can be followed for other libraries that does not follow modular approach [AMD spec]
Note: The above step of defining library modules can be avoided by using shim feature
Since your page is dynamic, you never know what modules will be loaded.
You can invoke multiple require() calls to load modules. Since requirejs load’s scripts asynchronously, the below approach will not harm your page performance.
Module-1 with in HTML view
File: scripts/widgets/module_1.js
Module 2 with-in HTML view
File: scripts/widgets/module_2.js
If you do not mind initializing the module after DOM load, you could use controljs and change the MIME type of the script tags. I believe that would not make too much of difference on the page performance.