I am working on integrating a javascript compiler into my web framework, and am running into a bit of a snag.
When running in development mode, all javascript modules are loaded individualy by ajax, but when switching to production mode, it compiles multiple modules into one file to reduce the number of HTTP requests. Each module can call a function to 'require' another module.
The problem I have is if moduleA requires moduleB, and moduleB is not loaded, it makes an ajax request. Consider the following code sample (extremely simplified), where moduleA and moduleB are compiled together. moduleA requires moduleB, and moduleB has not been loaded by that point in the script, so it makes an ajax request. A few lines later moduleB is run, and so it has been run twice.
/* compiled script file (multiple files combined) */
util.require = function(moduleName) {
if (moduleIsNotLoaded(moduleName)) {
loadByAjax(moduleName);
}
}
/* start module a */
util.require('moduleB');
moduleB.func();
/* end module a */
util.setModuleLoaded('moduleA');
/* start module b */
moduleB.func = function() {
alert('hello world');
};
bind_some_event();
/* end module b */
util.setModuleLoaded('moduleB');
This is unnacceptable because it defeats the initial purpose of reducing HTTP requests, and some modules bind event handlers, which cannot be bound twice. Some modules are not only function definitions and have code that is immediatly run.
Is there a way that I can force all modules to be available and registered as loaded, without actually running the code inside each module until the entire file has been run? I understand there is probably not a simple solution, and may require a paradigm shift.