javascript - 跨域或 CDN 加载 Mustache.js/Handlebars.js 模板的最佳实践

标签 javascript ajax cross-browser cross-domain mustache

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

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

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

我致力于优化加载顺序(有效)

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

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

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

使用 YQL 会很慢。

我可以以某种方式做 JSONP 所做的事情,但是使用 XMLXHTMLHTML,显然没有 javascript 回调?也许模板的末尾可以有一个小的回调函数,但我不想包装整个内容并且需要将其转义为 json。

最佳答案

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

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

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

So if the text plugin determines that the request for the resource is on another domain, it will try to access a ".js" version of the resource by using a script tag. Script tag GET requests are allowed across domains. The .js version of the resource should just be a script with a define() call in it that returns a string for the module value.

Example: if the resource is 'text!example.html' and that resolves to a path on another web domain, the text plugin will do a script tag load for '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 构建器会将所有这些内容包含在一个文件中。

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

关于javascript - 跨域或 CDN 加载 Mustache.js/Handlebars.js 模板的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14572811/

相关文章:

javascript:在一段时间后中断递归调用

cross-browser - HTML 电子邮件无法在 Google Apps/Gmail 中正确显示

javascript - 监听向上滑动手势的代码不起作用

javascript - Twitter Bootstrap Datepicker 不会更新输入值

javascript - 如何正确记录通过 Ajax 加载的内容

javascript - jQuery ajax load() 的错误处理

javascript - SAAS 每席位认证

javascript - 如何在 chrome 浏览器和 firefox 浏览器中验证日期

jquery - SCRIPT5 : Access is denied. 在 IE 上使用 parse.js 时

javascript - 如何从 UTC 日期时间戳中删除时间戳