【问题标题】:Best Practices for Loading Mustache.js/ Handlebars.js Templates Cross Domain or CDN加载 Mustache.js/Handlebars.js 模板跨域或 CDN 的最佳实践
【发布时间】:2013-01-12 10:15:44
【问题描述】:

这实际上并不是 Mustache.js 或 Handlebars.js 特定的问题,但如果您尝试优化 Web 应用的性能加载模板,这两个框架都会遇到此问题。

现在我正在从与应用程序的其余部分相同的域加载模板,但如果可能的话,我想从 CDN 加载我的模板。最大的问题是我不能跨浏览器不能通过 AJAX 加载文本文件。

我可以尝试哪些其他方法来优化单个模板跨域的加载时间?

我一直致力于优化加载顺序(工作)

将模板作为 xdomain 脚本文件加载到头部 (失败)

<script type='text/html' src="http://domain.cdn.com"></script>

我认为对 COR 的支持将受限于浏览器的数量。

使用 YQL 会很慢。

我能否以某种方式执行 JSONP 的功能,但使用 XMLXHTMLHTML,显然没有 javascript 回调?也许模板的末尾可以有一个小的回调函数,但我不想包装整个东西,需要将它转义为 json。

【问题讨论】:

标签: javascript ajax cross-browser cross-domain mustache


【解决方案1】:

我脑子里突然冒出一个想法。

使用 RequireJS 来build the templates into a single file。每个模板都将被包装为一个定义模块,并且该模板将被正确地转义为一个字符串。

因为文件是.js,所以可以正常从另一个域加载

所以如果文本插件确定对资源的请求是 在另一个域上,它将尝试访问“.js”版本的 资源通过使用脚本标签。允许脚本标签 GET 请求 跨域。资源的 .js 版本应该只是 带有 define() 调用的脚本,它返回模块的字符串 价值。

示例:如果资源是 'text!example.html' 并且解析为 另一个 web 域上的路径,文本插件将执行脚本标签加载 对于“example.html.js”。

https://github.com/requirejs/text#xhr-restrictions

如果你也compiled your Mustache/Handlebars templates 它会更高效。这是an example of a compiled Handlebars template wrapped in a define call。 Handlebars 编译器会处理输出,然后 RequireJS 构建器会将它们全部包含在一个文件中。

同样,没有尝试过这个解决方案,但可能会让你走上正轨。

【讨论】:

  • 您能否提供一个示例,说明如何将所有 HTML 模板文件合并到一个 JS 文件中?如果我需要花费 1-2 周的时间来了解如何使用 require.js,那么您的回答并没有多大意义。这是一个广泛而复杂的工具。
【解决方案2】:

我知道我正在尝试回答一个老问题.. 这可以通过将模板字符串嵌入到静态 HTML 文档中来实现,该文档包含在属性 type="text/x-handlebars-template" 的元素中。这被称为微模板。由于 type 属性,浏览器不会尝试执行脚本。比如——

<script id="list-template" type="text/x-handlebars-template">
    <p>YUI is brought to you by:</p>

    <ul>
        {{#items}}
            <li><a href="{{url}}">{{name}}</a></li>
        {{/items}}
    </ul>
</script>

完成后,我们必须编译,然后通过数据对象渲染它。

<script>
YUI().use('handlebars', 'node-base', function (Y) {
// Extract the template string and compile it into a reusable function.
var source   = Y.one('#list-template').getHTML(),
    template = Y.Handlebars.compile(source),
    html;

// Render the template to HTML using the specified data.
html = template({
    items: [
        {name: 'pie', url: 'http://pieisgood.org/'},
        {name: 'mountain dew', url: 'http://www.mountaindew.com/'},
        {name: 'kittens', url: 'http://www.flickr.com/search/?q=kittens'},
        {name: 'rainbows', url: 'http://www.youtube.com/watch?v=OQSNhk5ICTI'}
    ]
});

// Append the rendered template to the page.
Y.one('body').append(html);

});

详情请看这里-http://yuilibrary.com/yui/docs/handlebars/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2017-03-05
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2010-11-11
    • 2011-04-18
    相关资源
    最近更新 更多