Why do concatenated RequireJS AMD modules need a loader? Why do concatenated RequireJS AMD modules need a loader? javascript javascript

Why do concatenated RequireJS AMD modules need a loader?


An AMD optimiser has the scope to optimise more than the number of files to be downloaded, it can also optimise the number of modules loaded in memory.

For example, if you have 10 modules and can optimise them to 1 file, then you have saved yourself 9 downloads.

If Page1 uses all 10 modules then that's great. But what if Page2 only uses 1? An AMD loader can delay the execution of the 'factory function' until a module is require'd. Therefore, Page2 only triggers a single 'factory function' to execute.

If each module consumes 100kb of memory upon being require'd, then an AMD framework that has runtime optimisation will also save us 900kb of memory on Page2.

An example of this could be an 'About Box' style dialog. Where the very execution of it is delayed until the very last second as it won't be accessed in 99% of cases. E.g. (in loose jQuery syntax):

aboutBoxBtn.click(function () {    require(['aboutBox'], function (aboutBox) {        aboutBox.show();    }});

You save the expense of creating the JS objects and DOM associated with the 'About Box' until you are sure it's necessary.

For more info, see Delay executing defines until first require for requirejs's take on this.


The only real benefit is if you use modules across sections so there's a benefit to caching modules independently.


I had the same need, so I created a simple AMD "compiler" for that purpose that does just that. You can get it at https://github.com/amitayh/amd-compiler

Please note that it has many features missing, but it does the job (at least for me). Feel free to contribute to the codebase.