如何使用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 {}; } } });
解决方法
您可以在现有模块中要求文件.因此,当有人点击链接时,您可以触发执行以下操作的功能:
// 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(); }); }); });