0

I my webapp I use about 30 js files, each file containing 1 function. All these function are now selfinvoking and have references to each other.

The problem with this is that the order of scripts in the index.jsp matters. If a method is called on a function which has not been invoked yet we get a undefined error.

For a while we could overcome this by controlling the order of the <script> tags, but I would like to do this by using a loader script.

I have set up a small fiddle to show my concept. My biggest concern is that I have to declare my objects globally, in order to have them be accessible in the jquery(document).ready() function.

Is this an OK pattern? Any hints highly appreciated!

4

2 回答 2

2

您可以使用RequireJS或类似的加载器,它们会为您处理脚本依赖项。

您需要修改每个 JS 文件以使其成为与此示例类似的模块:

// File: module3.js
define(["module1", "module2"], function(m1, m2) {
    // Here, module1 and module2 are guaranteed to be loaded.
});

然后,您将制作一个“主”脚本(我通常称之为main.js)并需要几个模块:

require(["module3"], function (m3) {
  // Here module3 is loaded, as well as module1 and module2 
  // - because module3 depends on them.
});

并将其放入您的 HTML 中:

<script data-main="scripts/main" src="scripts/require.js"></script>
于 2013-11-13T11:22:11.430 回答
0

尝试构建您的服务器端架构,以便为每个页面提供正确的 js 文件(和其他静态文件)。为页面创建 1 个缩小的 js 文件并在 html 文件中初始化对象范围。

于 2013-11-13T11:27:03.727 回答