我是小站长 發表於 2019-6-1 19:58:21

基于 JS artTemplate 模板引擎 Template 加载的优化

<font face="Tahoma, &amp;quot"><font color="#333333">artTemplate (http://aui.github.io/artTemplate)一种全新的 javascript 模板引擎,它采用了预编译的方式让性能有了质的飞跃,并充分利用 javascript 引擎特性,使得其性能无论在前端还是后端都有极其出色的表现。但是在实际应用中我们发现,和Ajax配合后通常会产生很多的 Template,这些 Template 都堆积在页面源码中时间一长难免会越来越多,影响页面加载的字节数,让页面越来越大。</font></font><font face="Tahoma, &amp;quot"><font color="#333333">我们对此进行了优化,由于我们的业务主要是针对移动产品的,因此我们可以放心的使用 HTML5 的 localStorage 进行缓存操作,缓存部分代码如下:</font></font><font face="Tahoma, &amp;quot"><font color="#333333"><ol><li>artTemplate (http://aui.github.io/artTemplate)一种全新的 javascript 模板引擎,它采用了预编译的方式让性能有了质的飞跃,并充分利用 javascript 引擎特性,使得其性能无论在前端还是后端都有极其出色的表现。但是在实际应用中我们发现,和Ajax配合后通常会产生很多的 Template,这些 Template 都堆积在页面源码中时间一长难免会越来越多,影响页面加载的字节数,让页面越来越大。<br /><li>我们对此进行了优化,由于我们的业务主要是针对移动产品的,因此我们可以放心的使用 HTML5 的 localStorage 进行缓存操作,缓存部分代码如下:</ol>这时,我们可以把诸多的 Template 分门别类的存放在不同的文件中,比如把首页的 Template 代码存放在 tpl_index.html 中,列表页的 Template 代码存放在 tpl_list.html 中。每个文件中可以放多个 Template 定义,文件内容如下:</font></font><font face="Tahoma, &amp;quot"><font color="#333333"><ol><li>&lt;script id=&quot;header&quot; type=&quot;text/html&quot;&gt;<br /><li>&lt;div class=&quot;header&quot;&gt;&lt;h3&gt;&lt;%= header.name %&gt;&lt;/h3&gt;&lt;/div&gt;<br /><li>&lt;/script&gt;<br /><li><br /><li>&lt;script id=&quot;hotList&quot; type=&quot;text/html&quot;&gt;<br /><li>&lt;ul&gt;<br /><li>&nbsp; &nbsp; &lt;% for(i = 0; i &lt; list.length; i++){ %&gt;<br /><li>&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&lt;li tid=&quot;&lt;%= list.tid %&gt;&quot;&gt;&lt;%= list.subject %&gt;&lt;/li&gt;<br /><li>&nbsp; &nbsp; &lt;% } %&gt;<br /><li>&lt;/ul&gt;<br /><li>&lt;/script&gt;<br /><li><br /><li>······</ol>在我们使用的时候,直接引用文件即可,如下:</font></font><font face="Tahoma, &amp;quot"><font color="#333333"><ol><li>TC.load(&quot;tmpl/tpl_list.html&quot;);</ol><font color="#444444"><font color="#333333">首次访问此函数时,会调用 tmpl/tpl_list.html 文件并缓存到 localStorage 中,以后会直接从 localStorage 中获取 Template 的内容,直到 TC.VERSION 中的值变化,才会重新调用文件。从而减少了主页面请求的字节数。</font></font><font color="#444444"><font color="#333333">用过 artTemplate 的人会习惯直接把一些内容很短的模板直接写在 JS 里,类似下面</font></font><font color="#444444"><font color="#333333"><ol><li>template.compile('header', '&lt;div class=&quot;header&quot;&gt;&lt;h3&gt;&lt;%= header.name %&gt;&lt;/h3&gt;&lt;/div&gt;');</ol><font color="#444444"><font color="#333333">当然这样更省事。</font></font><font color="#444444"><font color="#333333">此方案的是保证减少页面请求字节及页面请求数的目的下还能做到方便维护而提供的!</font></font><font color="#444444"><font color="#333333"><br /></font></font><font color="#444444"><font color="#001000">此功能在打通版微社区中实现!</font></font><font color="#001000"><br /></font><br /></font></font></font></font><br />页面
頁: [1]
查看完整版本: 基于 JS artTemplate 模板引擎 Template 加载的优化