Javascript backbone.js默认情况下加载所有模板
我的项目几乎与此相似Javascript backbone.js默认情况下加载所有模板,javascript,performance,templates,backbone.js,Javascript,Performance,Templates,Backbone.js,我的项目几乎与此相似 但是,我的应用程序默认下载所有模板 ('text!templates/projects/list.html')。这是正确的吗 我的印象是除非你调用 路由器导航列表中的特定项,它不会加载视图、集合和模板文件。我在同一页吗 例如,如果我路由“sample.com/users”,它应该只加载与此“user”路由器规范关联的集合和视图。如果我错了,请纠正我 Raja KRequireJS通过定义所有模块的依赖项来工作。由于main.js需要app才能执行其他操作,因此它将首先加载a
但是,我的应用程序默认下载所有模板 ('text!templates/projects/list.html')。这是正确的吗 我的印象是除非你调用 路由器导航列表中的特定项,它不会加载视图、集合和模板文件。我在同一页吗 例如,如果我路由“sample.com/users”,它应该只加载与此“user”路由器规范关联的集合和视图。如果我错了,请纠正我
Raja KRequireJS通过定义所有模块的依赖项来工作。由于
main.js
需要app
才能执行其他操作,因此它将首先加载app
依赖的所有文件。由于应用程序
需要在路由器
中,而路由器
需要项目列表视图
,而项目列表视图
需要其基于文本的模板,因此这些文件都会在发生任何事情之前加载;RequireJS首先确保define(…)
或require(…)
函数中的每个回调都有它所需要的。这是意料之中的
如果要将文件的加载推迟到视图的实际创建,则应采用不同的视图结构。这让事情变得复杂了很多,这就是为什么大多数人不这么做的原因
下面是示例应用程序中ProjectListView
的一个选项。它用于提供处理模板异步加载的承诺。这有一个不幸的副作用,即使渲染
函数也异步,因为它可能需要等待模板文件出现。还是
define([
'jquery',
'underscore',
'backbone',
'when'
], function($, _, Backbone, when){
var ProjectListView = Backbone.View.extend({
el: $('#container'),
initialize: function() {
// Load the template file upon the creation of the view
this._ensureTemplateLoaded();
},
// This returns a Promise that will be resolved after the
// template file is loaded.
_ensureTemplateLoaded: function() {
var self = this;
return when.promise(function(resolve) {
// Require in the template. Note that this is
// a no-op if the template has been loaded previously
require([
'text!templates/project/list.html'
], function(projectListTemplate) {
// Resolve our promise, providing the template
resolve(projectListTemplate);
});
});
},
render: function(){
// Wait for the promise to be resolved to make sure
// we have loaded the template before attempting to render
var self = this;
this._ensureTemplateLoaded().then(function(projectListTemplate) {
// Huzzah! Now we can do the regular rendering with the
// template provided by the Promise
var data = {};
var compiledTemplate = _.template( projectListTemplate, data );
// Append our compiled template to this Views "el"
self.$el.append( compiledTemplate );
});
}
});
// Our module now returns our view
return ProjectListView;
});
如前所述,它有点复杂。除非加载大量文件,否则对最终用户的好处非常小
最后,请注意,RequireJS的优化器,r.js
,可以通过构建多个完全组装的js模块(即目标模块及其所有依赖项)来有效地完成相同的任务。然而,这通常意味着客户端将多次下载相同的JS,因此它也仅用于分离大型应用程序的不同组件
.谢谢。我还有一个建议,可以通过$.get加载模板,看起来很有效。很好。