如何使用RequireJS构建多个页面

时间:2011-05-31 08:15:04

标签: module requirejs

如何使用RequireJS构建多个页面?就像下面的示例一样,声明app.js中的每个类都是正确的做法吗?每个html文件都要声明<script data-main="src/main" src="src/require.js"></script>吗?

我想避免的是在用户到达网站的第一页时加载所有脚本。

main.js定义所有外部依赖项:

require(
    {
        baseUrl:'/src'
    },
    [
        "require",
        "order!http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js",
        "order!http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js",
        "order!http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js",
        "order!http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"
    ], 
    function (require) {
        require(["app"], function (app) {
            app.start();
        });
    }
);

定义每个组件的app.js文件:

define([ "product/ProductSearchView",
         "product/ProductCollection"
         ], function (ProductSearchView,
                      ProductCollection) {
         return {
             start: function() {
                  var products = new ProductCollection();
                  var searchView = new ProductSearchView({ collection: products });
                  products.fetch();
                  return {};
             }
        }
});

2 个答案:

答案 0 :(得分:9)

您可以在现有模块中要求文件。因此,当有人点击链接时,您可以触发执行以下操作的功能:

// If you have a require in your other module
// The other module will execute its own logic
require(["module/one"], function(One) {
    $("a").click(function() {
        require(["new/module"]);
    });
});

// If you have a define in your other module
// You will need to add the variable to the require
// so you can access its methods and properties
require(["module/one"], function(One) {
    $("a").click(function() {
        require(["new/module"], function(NewModule) {
            NewModule.doSomething();
        });
    });
});

答案 1 :(得分:3)

这是一个完整的例子,说明这一切是如何运作的; require.jsorder.js与应用程序的JS文件位于同一目录中。

<html> 
  <head>  
    <script data-main="js/test" src="js/require.js"></script>
  </head> 
  <body> 
    <button>Clickme</button>
  </body> 
</html>

test.js(在js文件夹中)

require(
  {
    baseUrl:'/js'
  },
  [
    "order!//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js",
    "order!//ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"
  ], 
  function () {
    require(["app"], function (app) {
      app.start();
    });
  }
);

app.js(在js文件夹中),按需加载Employee.js:

define([], function () {
  return {
    start: function() {
      $('button').button();
      $('button').click(function() {
        require(['Employee'], function(Employee) {
          var john = new Employee('John', 'Smith');
          console.log(john);
          john.wep();
        });
      });

      return {};
    }
  }
});

Employee.js(在js文件夹中):

define('Employee', function () {
  return function Employee(first, last) {
    this.first = first; 
    this.last = last;
    this.wep = function() {
        console.log('wee');
    }
  };
});