【发布时间】:2011-05-09 19:41:52
【问题描述】:
我正在使用 Jquery 模板来显示传入的 JSON 数据 我想将模板加载到可缓存的外部文件中。我该怎么做?
更新
http://encosia.com/2010/12/02/jquery-templates-composite-rendering-and-remote-loading/
非常接近我最终得到的解决方案,我只是使用了 iframe;
【问题讨论】:
我正在使用 Jquery 模板来显示传入的 JSON 数据 我想将模板加载到可缓存的外部文件中。我该怎么做?
更新
http://encosia.com/2010/12/02/jquery-templates-composite-rendering-and-remote-loading/
非常接近我最终得到的解决方案,我只是使用了 iframe;
【问题讨论】:
【讨论】:
也许这段代码可以提供帮助:
<script id="entry_show_template" defer type="text/html">
<div class="entry">
Age: <span class="age"></span> <a class="name" href="#"></a>
</div>
</script>
也许您也可以将此代码与 src 属性一起使用,这样可以访问脚本:
$('#entry_show_template')
【讨论】:
似乎有几种技术可以实现这一点,每种技术都有其优点/缺点。
1) 使用内联脚本块。这将在每个页面加载时带来模板块。如果父页面不可缓存,则可能会因多个模板而变得繁重
2) 通过外部 javascript 文件中的全局变量对象访问模板。这是可缓存的,但模板字符串变得难以破译
3) 模板字符串是 JSON 响应的一部分。这就引出了一个问题,为什么不做服务器端模板呢?
4) 使用静态 iframe 并在 iframe 加载时编译模板 - 这是可缓存的,模板是可读/可编辑的,如果将静态元素放在另一个域中,同源策略可能会出现问题
我最终选择了 iframe 方法,但经验不足,无法了解所有陷阱。
谢谢
【讨论】:
我对服务器端资源使用 ajax 调用,本例中为 aspx
$.ajax({
url: "myprog.aspx",
data: { whichTemplate: "template I'm Looking for" },
success: function(result) {
// result is the text string containing either a single template or a delimated list of templates
$.template('templatename', result);
} ,
dataType: "text"
});
【讨论】:
查看我对jQuery templates - where should I put them?的回答
除了您在问题中提到的the article from Dave Ward 之外,它还引用了An Introduction to jQuery Templates, by Stephen Walther 的一些额外技巧。特别是,它涵盖了如何获取模板一次并缓存它的编译版本。
【讨论】: