回顾

  • Micro-Templating

出自John Resig 2008年的一片文章,以及其经典实现:

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
var cache = {}; this.tmpl = function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){}
"with(obj){p.push('" + // Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');"); // Provide some basic currying to the user
return data ? fn( data ) : fn;
};
})();
  1. 基本的replace生成代码,终端动态编译方案
  2. 使用with解决context问题
  • Mustache.js & othors

更加丰富的模版语法,以及更加容易扩展。

/**
* Breaks up the given `template` string into a tree of tokens. If the `tags`
* argument is given here it must be an array with two string values: the
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
* course, the default is to use mustaches (i.e. mustache.tags).
*
* A token is an array with at least 4 elements. The first element is the
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
* all text that appears outside a symbol this element is "text".
*
* The second element of a token is its "value". For mustache tags this is
* whatever else was inside the tag besides the opening symbol. For text tokens
* this is the text itself.
*
* The third and fourth elements of the token are the start and end indices,
* respectively, of the token in the original template.
*
* Tokens that are the root node of a subtree contain two more elements: 1) an
* array of tokens in the subtree and 2) the index in the original template at
* which the closing tag for that section begins.
*/

我们可以从这段备注中简单的看出Mustache.js的编译原理。

性能优化之路

模版引擎成功将动态HTML代码从Javascript中分离出来,避免了从前频繁的Javascript代码中的字符串拼接,简化了编码工作,实则是前端发展的大跃进。但当部分人还在痴迷与模版引擎的功能时,已经有人朝性能方向迈进。

  • 缓存技术

每次将Template字符串转化成函数己经变成一种浪费,缓存简单说是编译后将函数cache起来,仅此而已。

  • context预赋值

为了避免使用with这种效率较低的方法而出现的,简单的说就是把传入的数据对象中的所有节点都变成局部变量,下面是一个简单的例子:

var compile = function(str){
//避免with语法
var strFn = "var _$jstpl='',__fn__=(function(__d__){var __v__='';for(var __k__ in __d__){__v__+=('var '+__k__+'=__d__[\"'+__k__+'\"];');};eval(__v__);_$jstpl+='" + parse(str) + "';__v__=null;})(param);__fn__ = null;return _$jstpl;";
return new Function("param", strFn);
};
  • 规范关键字

作为最快的模版引擎,doT根本不使用with,而是直接通过规范关键字传入参数为it,然后所有参数都用it的节点来引用。

  • 线下编译

浏览器编译过程转为线下,直接生成执行函数。

  • 拼接方法

字符串拼接方法一般有:

  1. arr.push & arr.join
  2. res += tmp
  3. res = res + tmp

很多人误以为数组 push 方法拼接字符串会比 += 快,要知道这仅仅是 IE6-8 的浏览器下。实测表明现代浏览器使用 += 会比数组 push 方法快,而在 v8 引擎中,使用 += 方式比数组拼接快 4.7 倍。最新的一些测试结果还发现res = res + tmp在v8某些版本甚至比res += tmp还快。

未来

有些时候流行总在轮回,比如黑框眼睛以前是我们奶奶那辈人戴的,但现在年轻人都开始戴了。

模版从后端render,变成前端render,变成线下render……现在又随着NodeJS的崛起回来了后端(前台?)render,部分大公司如:FacebookGoogle已经线上应用。

Javascript模版引擎简介的更多相关文章

  1. 简单JavaScript模版引擎优化

    在上篇博客最简单的JavaScript模板引擎 说了一下一个最简单的JavaScript模版引擎的原理与实现,作出了一个简陋的版本,今天优化一下,使之能够胜任日常拼接html工作,先把上次写的模版函数 ...

  2. Javascript模版引擎mustache.js简介

    背景 最近使用ELK的sentinl进行告警配置,sentinl的邮件通知支持mustache,借此机会学习了mustache相关知识,记录在此. mustache的思想 mustache的核心是标签 ...

  3. 最简单的JavaScript模板引擎

    在小公司待久了感觉自己的知识面很小,最近逛博客园和一些技术网站看大家在说JavaScript模版引擎的事儿,完全没有概念,网上一搜这是08年开始流行起来的...本来以为这是很高深的知识,后来在网上看到 ...

  4. 探究Javascript模板引擎mustache.js使用方法

    这篇文章主要为大家介绍了Javascript模板引擎mustache.js使用方法,mustache.js是一个简单强大的Javascript模板引擎,使用它可以简化在js代码中的html编写,压缩后 ...

  5. JST(JavaScript Trimpath)前端模板引擎简介

    JST(JavaScript Trimpath)前端模板引擎简介及应用 今天在做某系统日志列表的时候用到了这个玩意儿.刚开始只是根据别人的例子照葫芦画瓢完成了日志列表及对应详情,晚上有空了才仔细去网上 ...

  6. 【转载】Asp.Net中使用基于jQuery的javascript前台模版引擎JTemplate

    JTemplate是基于jQuery的开源的前端模版引擎,在Jtemplate模板中可以使用if判断.foreach循环.for循环等操作,使用Jtemplate模板优点在于ajax局部刷新界面时候不 ...

  7. JavaScript模板引擎实例应用

    在之前的一篇名为<移动端基于HTML模板和JSON数据的JavaScript交互>的文章中,我向大家说明了为什么要使用JavaScript模板以及如何使用,文末还提到了laytpl.art ...

  8. Nodejs学习笔记(五)--- Express安装入门与模版引擎ejs

    目录 前言 Express简介和安装 运行第一个基于express框架的Web 模版引擎 ejs express项目结构 express项目分析 app.set(name,value) app.use ...

  9. javascript模板引擎Mustache

    Mustache(英文本意:触须,胡须)是基于JavaScript实现的模版引擎,类似于JQuery Template,但是这个模版更加的轻量级,语法更加的简单易用,很容易上手. 下载:https:/ ...

随机推荐

  1. class.forName的作用?

    调用该访问 返回一个以字符串指定类名的类的对象. 返回字节码,返回字节码的方式有几种: ①:这份字节码曾经被加载过已经存在java虚拟机中了直接返回. ②:java虚拟机中还没有这份字节码,用类加载器 ...

  2. 7,EasyNetQ-控制队列名称

    EasyNetQ在为队列生成名称时的默认行为是使用   消息类型名称+subscription Id 例如,名称空间EasyNetQ.Tests.Integration中的PartyInvitatio ...

  3. 潭州课堂25班:Ph201805201 爬虫高级 第三课 sclapy 框架 腾讯 招聘案例 (课堂笔记)

    到指定目录下,创建个项目 进到 spiders 目录 创建执行文件,并命名 运行调试 执行代码,: # -*- coding: utf-8 -*- import scrapy from ..items ...

  4. socket 远程命令

    # -*- coding: utf-8 -*- # 斌彬电脑 from socket import * import subprocess server = socket(AF_INET, SOCK_ ...

  5. 2、函数y=f(x)

    /* Note:Your choice is C IDE */ #include "stdio.h" /* 3.函数y=f(x)可表示为: */ void main() { int ...

  6. fastJson解析复杂的json字符串,经测试已经成功解析

    要解析的json数据格式为: HTTP/1.1 200 OK Content-Type: text/jsv Content-Length: length { ResponseStatus: { }, ...

  7. java程序的种类有三种

    Application―Java应用程序”是可以独立运行的Java程序.由Java解释器控制执行.Applet  ―Java小程序”不能独立运行(嵌入到Web页中).  由Java兼容浏览器控制执行. ...

  8. 修改button的可点击区域

    需求:在cocos2dx引擎中,button的点击区域和button图片的大小是一样的,但是我需要修改可点击区域的大小和位置,需要修改引擎源码: button提供的接口中并没有和touch相关,but ...

  9. The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build

    https://jingyan.baidu.com/album/f79b7cb34f40569144023ef9.html?picindex=1

  10. [Java] LinkedHashMap 源码简要分析

    特点 * 各个元素不仅仅按照HashMap的结构存储,而且每个元素包含了before/after指针,通过一个头元素header,形成一个双向循环链表.使用循环链表,保存了元素插入的顺序. * 可设置 ...