Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript file load order and dependency management

Tags:

javascript

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 what i am going is ok first.

like image 395
Jason Miesionczek Avatar asked Feb 06 '11 17:02

Jason Miesionczek


1 Answers

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.

like image 143
Raynos Avatar answered Oct 05 '22 12:10

Raynos