开发者

prevent js module execution

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 开发者_StackOverflow社区each module until the entire file has been run? I understand there is probably not a simple solution, and may require a paradigm shift.


Our web app is made of modules too. The way it works may give you some ideas:

The most common modules, are embedded in the initial HTML page (HTML, JS, CSS, data images). The app start with that page(300-400kb, then from the cache), and a single HTTP call for data.
This makes the app start very quickly.

Then if the user choose a new module, not loaded yet. It gets it through an iframe. HTML, CSS and Javascript objects are imported by the parent page.

The new module is then started from the parent page too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜