如何加载有关当前页面的特定代码?

时间:2012-08-01 10:49:19

标签: javascript requirejs

我正在构建一个复杂的Web应用程序并且为了简单起见,我在各种文件中制作了各种模块(对象)。某些页面可能需要这些模块,而其他页面则不需要。

出于这个原因,我想避免为任何页面加载所有模块,增加无用请求的数量。

到目前为止,我的工作方式如下:

  1. 我包含所有所需的
  2. 之后,我在jQuery(function() {});中使用特定的#ids或.classes参数为当前页面实例化这些库;
  3. 一切正常,但由于我的应用程序越来越容易,我想用RequireJS管理我的JS。

    这就是我开始有点困惑的地方。

    我知道我可以在需要时使用require(['module1', 'module2', 'etc'], function (module1, module2, etc) {})加载我的模块,但我怎么能说:

      

    “在此页面上,您加载这些模块,并使用那些#ids和.classes实例化它们”

      

    “在这个其他页面上,您只加载该模块,使用此#other-id”

    例如,

    module1将从api加载数据,并将它们列为以参数形式给出的特定表:

    // in page 1
    var mod1 = new Module1($('#content>table');
    mod1.init(); // will load the data from the api with the url located at <table data-api-url="http://....">
    
    // in page 2
    var mod1 = new Module1($('#content .items>table'); // The table where we want the data to be populated is not at the same position!
    mod1.init();
    

    这意味着,根据页面的不同,我将不得不加载我的模块。这就是我不知道如何使用RequireJs:/

    感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您需要的是每个页面的javascript文件。该文件将负责执行特定于页面的代码。

我假设您将使用r.js来优化和打包您的代码。

我们可以将Module1,Module2等解释为库,因为它们将在多个页面上使用。为避免浏览器对每个库模块执行一个请求,您可以在优化的文件中包含此模块:

配置构建配置文件的“modules:”属性,如下所示:

...
modules: [
   {
       name: "main" // this is your main file
       includes: [
          "module1",
          "module2",
          "etc..."
       ]
   }
]
...

通过执行此操作,您可以告诉requirejs类似于:优化我的“main.js”文件并在其中包含所有依赖项,还包括“module1”,“module2”等。 您必须执行此操作,因为在主文件中您没有在require()/ define()调用中包含这些模块,但您仍然希望它们可用于特定于页面的模块需要它们。您不必为每个库模块执行此操作,只需为大多数页面使用的库模块执行此操作。

然后,您为页面创建一个javascript文件以使用这些模块:

define(function(require, exports, module) {
   var $ = require("jquery"),
       module1 = require("module1");

   var mod1 = new Module1($('#content>table'));
   mod1.init();       

   //other page specific-code.
});

然后在html文件中:

<script data-main="main" data-start="home" src="require.js"></script>

因此,当页面加载时,它会发出require.js的请求,然后是main.js的另一个请求,然后是home.js的另一个请求。

我会为另一个问题添加链接,以便这个答案得到一些背景信息:How to use RequireJS build profile + r.js in a multi-page project

答案 1 :(得分:0)

RequireJS的创建者实际上创建了一个使用特定于页面的主文件的示例项目:https://github.com/requirejs/example-multipage