JavaScript file loading order and dependency management

Just wondering about it ...

I have several separate javascript files that contain code based on a module template. Some of the modules have some of the others as dependencies. If I know that none of the codes will be called in HTML until the page is loaded, is the file loading order maintained?

Is the fact that the module code is inside the immediate function sufficient to cause the requirement that other modules are already loaded?

I am ready to look into the RequireJS library if necessary, but just wanted to know if what I am doing is normal.

+7
source share
2 answers

If possible, configure your dependencies so that you can load and configure all your modules when loading a javascript file (i.e. use the self-launch function).

And then call .init or the equivalent function for all of your modules in the .ready block. Thus, you can explicitly call any functionality that requires dependency after loading all of your files.

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 has no dependencies can be executed in closing foo.js and bar.js , and any dependent code can be called through your init function on .ready after loading all the files.

+8
source

If all the files were downloaded at startup time, the order of loading does not matter.

It is possible that some JavaScript engines will start compiling scripts immediately after they are loaded, so this may affect this. But the scripts will still work!

+1
source

All Articles