JavaScript文件加载顺序和依赖关系管理

JavaScript文件加载顺序和依赖关系管理

本文介绍了JavaScript文件加载顺序和依赖关系管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道这个...

Just wondering about this...

我有几个单独的javascript文件,它们都包含基于模块模式的代码。一些模块将其他一些模块作为依赖项。如果我知道在加载页面之前不会在HTML上调用任何代码,那么加载文件的顺序是否仍然很重要?

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?

如果需要,我准备查看RequireJS库,但是我想先知道我的目标是否正常。

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.

推荐答案

如果可能的话,设置你的依赖项,这样你就可以加载和设置加载javascript文件时所有模块(即使用自执行函数)。

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).

然后调用 .init .ready 块中的所有模块上的$ c>或等效函数。这样,您可以在加载所有文件后显式调用任何需要依赖的功能。

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.

示例:

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
     });

}());

任何没有依赖项的代码都可以在 foo的闭包中执行。 js & bar.js 并且可以通过 .ready init 函数调用任何相关代码/ code>一旦加载了所有文件。

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.

这篇关于JavaScript文件加载顺序和依赖关系管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:35