2

来自https://github.com/ccoenraets/backbone-jax-cellar/blob/master/WebContent/js/utils.js

tpl = {

// Hash of preloaded templates for the app
templates: {},

// Recursively pre-load all the templates for the app.
// This implementation should be changed in a production environment. All the template files should be
// concatenated in a single file.
loadTemplates: function(names, callback) {

    var that = this;

    var loadTemplate = function(index) {
        var name = names[index];
        console.log('Loading template: ' + name);
        $.get('tpl/' + name + '.html', function(data) {
            that.templates[name] = data;
            index++;
            if (index < names.length) {
                loadTemplate(index);
            } else {
                callback();
            }
        });
    }

    loadTemplate(0);
},

// Get template by name from hash of preloaded templates
get: function(name) {
    return this.templates[name];
}
};

我应该做类似的事情吗

$.get('tpl/all-tpls.html', function(data) { }

获取所有的 html 模板?这不是不必要地获取一堆 html 吗?我们的应用程序是用 Java 构建的,我们正在使用https://github.com/samaxes/minify-maven-plugin来缩小和合并我们的 js 和 css 文件。任何方向将不胜感激。

4

1 回答 1

3

简短的回答:是的。您应该首先在应用程序加载时加载所有模板,以便它们可用。在生产中,这可以与提供正确的远期到期标头相结合,以便在用户访问之间(即 1 年)为用户缓存模板。然后,您可以使用查询字符串破坏缓存,例如tpl/all-tpls.html?v=001

更长的答案

出于性能原因,您很可能希望尽可能减少加载时间和请求数量。如果在模板已经可用的情况下加载新部分时延迟更少,这也将有助于应用程序感觉更灵敏。

在您的应用程序变得非常大之前,组合您的模板并缓存它们将是有效的。此时,您可能希望分解加载 - 例如基于应用程序部分的组。但是,将其视为生命周期性能优化 - 不要仅仅为了它而进行预优化。

于 2013-02-20T01:39:59.003 回答