【问题标题】:Backbone templates in production生产中的主干模板
【发布时间】:2013-02-19 20:46:11
【问题描述】:

来自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 文件。任何方向将不胜感激。

【问题讨论】:

  • Java 不是 JavaScript
  • 我们的后端运行在java上。
  • 不过,这个问题属于 JavaScript。如果您在服务器端使用 Java,对您有好处!但这根本不适合作为 Java 问题。
  • 如果你看到我的问题的结尾,链接是一个 Maven 插件,它的功能与我所追求的类似,仅适用于 JS 和 CSS 文件。

标签: javascript backbone.js underscore.js templating


【解决方案1】:

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

更长的答案

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

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

【讨论】:

  • 最好将模板预编译成 Javascript 并将其与应用程序的其余部分连接起来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-26
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多