如何使用 RequireJS 构建多个页面
如何使用RequireJS构建多个页面?就像下面的示例一样,在 app.js 中声明每个类是正确的做法吗?是否每个 html 文件都声明 ?
我想避免的是当用户到达网站的首页时加载所有脚本。
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 {};
}
}
});
How to structure multiple pages with RequireJS? Is, like the following sample, declaring every class in app.js is the right thing to do? Has every html file to declare the <script data-main="src/main" src="src/require.js"></script>
?
What I want to avoid is loading all the script when a user reach the first page of a site.
main.js defining all external dependencies:
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 file defining every component:
define([ "product/ProductSearchView",
"product/ProductCollection"
], function (ProductSearchView,
ProductCollection) {
return {
start: function() {
var products = new ProductCollection();
var searchView = new ProductSearchView({ collection: products });
products.fetch();
return {};
}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在现有模块中请求文件。因此,假设当有人单击链接时,您可以触发执行以下操作的函数:
You can require files within your existing module. So say when someone clicks a link you could trigger a function that does the following:
这是一个完整的例子,说明了这一切是如何运作的; require.js 和 order.js 与应用程序的 JS 文件位于同一目录中。
test.js(在 js 文件夹中)
app.js(在 js 文件夹中),按需加载 Employee.js:
Employee.js(在 js 文件夹中):
This is a complete example of how this all works; require.js and order.js are in the same directory as the app's JS files.
test.js (in js folder)
app.js (in js folder) with a on-demand load of Employee.js:
Employee.js (in js folder):