JavaScript file load order and dependency management
Just wondering about this...
I have several separate javascript files, that all contain code based on the module pattern. A few of the modules have some of the others as dependencies. If i know that none of the code would be called on the HTML until the page is loaded, does the order in which the files load still important?
Is the fact that the module code sits inside an immediate function enough to trigger the requirement that the other modules be loaded already?
I am prepared to look into the RequireJS library if need be, but just wanted to know if开发者_C百科 what i am going is ok first.
If possible set up your dependencies so you can load and set up all your modules when the javascript file gets loaded (i.e. use a self executing function).
And then call a .init
or equivalent function on all your modules in a .ready
block. That way you can explicitly call any functionality requiring dependencies after all your files have loaded.
An example:
foo.js
(function() {
function initFoo() { ... }
...
window.namespace.foo = {
init: initFoo
}
}());
bar.js
(function() {
function initBar() { ... }
...
window.namespace.bar = {
bar: initBar
}
}());
main.js
(function() {
$.ready(function() {
window.namespace.foo.init();
window.namespace.bar.bar(); // dependancies on foo
});
}());
Any code that doesnt have dependancies can be executed in the closures of foo.js
& bar.js
and any dependant code can be called through your init
function on .ready
once all the files have loaded.
If all of the files have been loaded by the time execution starts, the order of loading does not matter.
It might be possible that some JavaScript engines begin to compile scripts as soon as they are downloaded, so this might affect that. But the scripts will still run!
精彩评论