Home  >  Article  >  Web Front-end  >  JavaScript template engine-tmpl bug repair and performance optimization analysis_javascript skills

JavaScript template engine-tmpl bug repair and performance optimization analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:00:25963browse

There are many exquisite tmpl
front-end templates available in open source, but the “javascript micro templating” developed by jQuery author John Resig is the most exquisite. It realizes the core functions of the template engine in just a few strokes.
For its introduction and usage, please see the author's blog: http://ejohn.org/blog/javascript-micro-templating/
Let us take a look at his source code first:

Copy code The code is as follows:

(function(){
var cache = {};
this.tmpl = function (str, data){
var fn = !/W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str). innerHTML):
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};"
"with(obj ){p.push('"
str
.replace(/[rtn]/g, " ")
.split("<%").join("t")
.replace(/((^|%>)[^t]*)'/g, "$1r")
.replace(/t=(.*?)%>/g, "', $1,'")
.split("t").join("');")
.split("%>").join("p.push('")
.split("r").join("\'")
"');}return p.join('');");
return data ? fn( data ) : fn;
};
})();

Although the sparrow is small, it has all the internal organs. In addition to basic data attachment, it also has a caching mechanism and logic support. Now, if I were to rank the most energy-saving custom functions in JavaScript, the first place would be the $ function (document.getElementById short version), and the second place would be tmpl.
Of course, it is not perfect. I found some problems during use:
tmpl has a fly in the ointment
1. It cannot handle escape characters correctly, such as:
Copy code The code is as follows:
tmpl('<%=name%>//<%=id%> ', {name:'sugar Pie', id: '1987'});

It will report an error. If working properly, it should output: Sugar Cookie/1987
In fact, the solution is very simple, add a line of regex to escape the escape character:
Copy code The code is as follows:
str.replace(/\/g, "\\")

2. It sometimes cannot correctly distinguish the first parameter Is it an ID or a template.
If the page template ID is underlined, such as tmpl-photo-thumb, it will not look for the template with this name, and will think that the original template passed in is directly compiled and output.
The most intuitive difference between the original template and the element ID is whether it contains spaces, so just change the regular expression:
view sourceprint?1 !/s/.test(str)
3. It also has internal There is a code left for testing and can be deleted.
Copy code The code is as follows:
print=function(){p.push.apply(p,arguments );}

Doubts about tmpl efficiency
Until I read a soft article by Baidu mux introducing YayaTemplate some time ago, the author of the original article conducted efficiency tests on the major popular template engines, and finally concluded that YayaTemplate is the most popular template engine. A quick one. Although the test result of tmpl is not as good as YayaTemplate, it also allows me to dispel my concerns about performance. In actual application, it is almost the same as traditional string concatenation. There will be a large performance gap between them only when performing very large-scale analysis. (Super large-scale? JavaScript itself is not suitable for this. If one day a programmer inserts thousands of list data into the browser at one time and it is extremely slow, there is no doubt: the problem lies with this programmer, he is not Will cherish the user's browser. )
When it comes to engine efficiency rankings, I don't think this is the primary criterion for measuring template engines. Template syntax is also an important part. At this time, YayaTemplate's template syntax becomes obvious. Much more obscure, it uses a clever twist on template syntax to save a few regular expressions.
First show the source code of YayaTemplate:
Copy the code The code is as follows:

//author:yaya,jihu
//uloveit.com.cn/template
//how to use? YayaTemplate("xxx").render({});
var YayaTemplate = YayaTemplate || function(str){
//Core analysis method
var _analyze=function(text){
return text.replace(/{$(s|S)*?$} /g,function(s){
return s.replace(/("|\)/g,"\$1")
.replace("{$",'_s.push("')
.replace("$}",'");')
.replace(/{%([sS]*?)%}/g, '",$1,"')
}) .replace(/r|n/g,"");
};
//Intermediate code
var _temp = _analyze(document.getElementById(str)?document.getElementById(str).innerHTML: str);
//Return generator render method
return {
render : function(mapping){
var _a = [],_v = [],i;
for (i in mapping){
_a.push(i);
_v.push(mapping[i]);
}
return (new Function(_a,"var _s=[];" _temp " return _s;")).apply(null,_v).join("");
}
}
};

If the performance problem is raised to one A high-level attempt to solve the "academic problem", why is tmpl slower than YayaTemplate?
Grammar parsing? Although YayaTemplate uses a novel way of wrapping html with javascript, it ultimately needs to be parsed into a standard using regular expressions. JavaScript syntax, there will not be much difference in the efficiency of regularization, and both parties use a caching mechanism to ensure that the original template is only parsed once? The template engine will eventually save the data in the form of variables. In the closure so that the template can get it. Let’s first compare the variable declaration mechanisms of both parties:
YayaTemplate is implemented using the traditional method of passing parameters. It separates the name and value of the object by traversing the data object, and then uses the object member name as the parameter name of the new Function (that is, the variable name), and then uses the appley calling method of the function to pass those parameters.
tmpl is implemented using the with statement that is not commonly used in JavaScript. The implementation is very simple, omitting the var keyword.
The performance problem of tmpl lies in with. The with statement provided by javascript is intended to be used to access the properties of an object more quickly. Unfortunately, the presence of the with statement in the language severely slows down the JavaScript engine because it prevents lexical scoping of variable names.
Optimize tmpl
If tmpl removes the with statement and uses traditional parameter passing, the performance will be greatly improved immediately. After actual testing, under 240,000 pieces of data, Firefox can improve 5 times, Chrome 2.4 times, Opera 1.84 times, and Safari 2.1 times, IE6 1.1 times, IE9 1.35 times, and finally tied with YayaTemplate.
Test address: http://www.planeart.cn/demo/tmpl/tmpl.html
Tmpl optimized version final code:

Copy code The code is as follows:

/**
* Micro template engine tmpl 0.2
*
* 0.2 Update:
* 1. Fix the bug in escape character and id judgment
* 2. Abandon the inefficient with statement to achieve the highest improvement 3.5 times execution efficiency
* 3. Use random internal variables to prevent conflicts with template variables
*
* @author John Resig, Tang Bin
* @see http://ejohn.org/ blog/javascript-micro-templating/
* @name tmpl
* @param {String} Template content or element ID containing template content
* @param {Object} Additional data
* @return {String} Parsed template
*
* @example
* Method 1: Embed template in the page
*
* tmpl('tmpl-demo', {name: 'demo data', list: [202, 96, 133, 134]})
*
* method Two: Directly pass in the template:
* var demoTmpl =
* '
    '
    * '<% for (var i = 0, l = list.length; i < length; i ) { %>'
    * '
  1. <%=list[i]%>
  2. '
    * '<% } %>'
    * '
';
* var render = tmpl(demoTmpl);
* render({name: 'demo data', list: [ 202, 96, 133, 134]});
*
* The difference between these two methods is that the first one will automatically cache the compiled template,
* while the second cache is controlled by external objects , such as the render variable in Example 2.
*/
var tmpl = (function (cache, $) {
return function (str, data) {
var fn = !/s/. test(str)
? cache[str] = cache[str]
|| tmpl(document.getElementById(str).innerHTML)
: function (data) {
var i, variable = [$], value = [[]];
for (i in data) {
variable.push(i);
value.push(data[i]);
};
return (new Function(variable, fn.$))
.apply(data, value).join("");
};
fn.$ = fn.$ || $ " .push('"
str.replace(/\/g, "\\")
.replace(/[rtn]/g, " ")
.split("<%") .join("t")
.replace(/((^|%>)[^t]*)'/g, "$1r")
.replace(/t=(.*? )%>/g, "',$1,'")
.split("t").join("');")
.split("%>").join($ ".push('")
.split("r").join("\'")
"');return " $;
return data ? fn(data) : fn;
}})({}, '$' ( new Date));

The template engine relies on the Function constructor, which like eval provides a method to access the javascript parsing engine using text. This will also significantly reduce performance, but at this point there is no other way in JavaScript.
Using the Function constructor also imposes restrictions on parameter names, so the naming of data members must be consistent with the JavaScript variable name specifications, otherwise an error will be reported. Fortunately, this error can be discovered immediately during operation and will not become a landmine.
Tips for using tmpl
1. Cache optimization.
tmpl performs caching optimization on templates embedded in the page by default (that is, when the first parameter is an ID), it will only analyze the template once. If the original template is passed directly into the first parameter of tmpl and needs to be used multiple times, it is recommended to cache it with a public variable and use it again when the data needs to be parsed to obtain the same optimization effect. For example:
Copy code The code is as follows:

// Generate template cache
var render = tmpl(listTmpl);
//The template can be called multiple times
elem.innerHTML = render(data1);
elem.innerHTML = render(data2);
...

2. Avoid undefined variables causing system crash.
If a variable output is defined in the template, and the incoming data is missing this item, an undefined variable error will occur, causing the entire program to crash. If data integrity cannot be ensured, there are still ways to probe its members. In the original version, the implicit variable saves the original incoming data, that is, obj; in my upgraded version, it is the keyword this, such as:
Copy code The code is as follows:

<% if (this.dataName !== undefined) { %>
<%=dataName %>
< ;% } %>

3. 디버깅 템플릿.
템플릿 엔진은 텍스트를 사용하여 자바스크립트 엔진을 호출하기 때문에 디버깅 도구는 오류 줄을 찾을 수 없습니다. 업그레이드된 버전에서는 디버깅 도구를 사용하여 컴파일된 템플릿 캐시를 출력할 수 있습니다. 예를 들어 다음 템플릿을 디버그합니다.
코드 복사 코드는 다음과 같습니다.

< ;script id="tmpl " type="text/tmpl">

    <% for (var i = 0, l = list.length; i < l; i ) %>
  • <%=list[i].index%>. 사용자: <%=list[i].user%>; .site%>< ;/li>
    <% } %>


출력 캐시:
🎜>코드 복사 코드는 다음과 같습니다.
window.console(tmpl('tmpl').$)

로그 결과:

코드 복사 코드는 다음과 같습니다.
"$1318348744541 .push('
    ' ); for (var i = 0, l = list.length; i < l; i ) { $1318348744541.push('
  • ',list [i].index,'.사용자: ', list[i].user,'; 웹사이트:',list[i].site,'

  • ');

'); return $1318348744541"

이제 템플릿 엔진으로 컴파일된 javascript 문을 볼 수 있으며, 이에 대해 템플릿에 오류가 있는지 확인할 수 있습니다. ($1318348744541은 임의의 이름을 가진 임시 배열이므로 무시할 수 있습니다.)
마지막으로 tmpl의 원저자와 YayaTemplate의 저자의 노고에 깊은 감사를 드립니다. 구현 메커니즘을 분석하고 문제를 해결하며 그로부터 이익을 얻습니다. 혼자서 행복하는 것은 다른 사람과 함께하는 행복만큼 좋지 않습니다. 공유하십시오.
탕빈 – 2011.10.09 – 후난-창사
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn