Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Implementation and Optimization of Javascript template engine

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "the implementation and optimization of Javascript template engine". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "the implementation and optimization of Javascript template engine"!

Juicer-implementation and optimization of a Javascript template engine

Let's start with a piece of code and suppose there is a piece of JSON data like this:

Var json= {

Name: "running Fire"

Blog: "benben.cc"

}

We need to generate HTML code like this based on this JSON:

Streaming Fire (blog: benben.cc)

Traditional Javascript code must look like this:

Var html

Html=''+json.name+' (blog:'+ json.blog+')'

It goes without saying that such code is a mixture of html structure and code logic, and the code is not readable and not easy to maintain later, so there is a function like this:

Function sub (str,data) {

Return str

.replace (/ {(. *?)} / igm,function ($, $1) {

Return data [$1]? data [$1]: $

});

}

With this function, our work of concatenating strings can be simplified as follows:

Var tpl=' {name} (blog: {blog})'

Var html=sub (tpl,json)

See here, needless to say, I want to visually show the benefits of the front-end template engine through this example, which can completely peel off html and code logic, and facilitate multi-person collaboration and later code maintenance. Of course, when our business logic needs to loop through the data source, if judgment, etc., this concise function obviously can not meet our needs, so there are many template engines on the market today, such as Mustache, jQuery tmpl, Kissy template, ejs, doT, nTenjin, etc.

"do not add entities if it is not necessary." This is the famous Occam razor rule, which is simply to avoid repeating wheels. Then there will be children's shoes question, since there are so many ready-made things available, why re-create one?

Personally, I think a good template engine should take into account these points:

Concise grammar

High execution efficiency

Security.

Error handling mechanism

Multilingual versatility

However, the existing template engines in the market do not take into account the above points. For example, Mustache supports multiple languages, and its versatility is good, but its performance is poor, and its syntax does not support advanced features, such as unable to make if judgment or obtain index index values when traversing. JQuery tmpl depends on jQuery and lacks portability. Although Kissy template relies on Kissy, its performance and syntax are recommended. DoT/nTenjin performance and flexibility are very good. But the syntax needs to be written in native js, and the written template code is slightly less readable.

You can't have both, syntax processing, security output filtering and the introduction of error handling mechanisms will to some extent reduce the performance of the template engine, so we need to weigh. Juicer first regards performance as the first important indicator in its implementation. After all, performance has a direct impact on users' perception, while taking into account both security and error handling mechanisms (even if this leads to a slight performance degradation).

First of all, let's take a look at the performance comparison with several mainstream template engines on jsperf.

As you can see, the performance is better than the traditional template engine, the following introduction is mainly from the syntax, security and error handling, and how to use these aspects of Juicer.

a. Grammar

Loop {@ each}... {@ / each}

Judge {@ if}... {@ else if}... {@ else}... {@ / if}

Variable (function supported) ${varname | function}

Comment {# comment here}

For detailed syntax, please refer to Juicer Docs.

b. Security.

Security, to put it simply, is to escape and filter the output data before output, to avoid script injection attacks such as XSS, and simply sweep away blindness. take the example of XSS.

Var json= {

Output:'alert ("XSS");'

}

If the JSON data is returned by a third-party interface or contains user input (such as BBS, evaluation), we will execute malicious js code if we write output to the page, so Juicer is safely escaped to the data output by default. Of course, if you don't want to be escaped, you can use ${varname}.

Juicer.to_html ('${output}', json); / / output: alert ("XSS")

Juicer.to_html ('${output}', json); / / output: alert ("XSS")

c. Error handling

If there is no error handling, when the template engine compilation (Compile) or rendering (Render) error will cause subsequent js code to stop execution, it is conceivable that if the entire page hangs due to a comma or occasional error in JSON data, it is unacceptable. However, when Juicer encounters these errors, it will not affect the execution of the subsequent code. It will only issue a Warn on the console to inform the developer that there is an error in the parsing of the template.

Juicer.to_html ('${varname,}', json)

Alert ('hello, Juicerbread')

Execute the above code and you will see the "Juicer Compile Exception: Unexpected token," typed by the console, but the subsequent alert will not be blocked due to errors.

Realization principle

Juicer compiles and renders a template in the following steps:

1. Syntax analysis of the template code

2. Generate the native Javascript code string after analysis

3. Convert the generated code into reusable Function (Compiled Template)

Var json= {

List: [

{name: "benben"}

{name: "liuhuo"}

]

}

Var tpl=' {@ each data.list as value,key} ${value.name} {@ / each}'

Var compiled_tpl=juicer.compile (tpl, {errorhandling:false})

Let's take a look at the compiled code through compiled_tpl.render.toString ():

Function anonymous (data) {

Var data = data | | {}

Var out =''

Out + =''

For (var i0 = 0, l = data.list.length; i0 < l; i0 others +) {

Var value = data.list [i0]

Var key = i0

Out + =''

Out + = ((value.name))

Out + =''

}

Out + =''

Return out

}

Do you already understand the principle of Juicer? This compiled function will help us assemble from the data to the html code each time.

Here are a few optimizations worth sharing:

1. Using + = instead of array.push

2 、 avoid using with {}

3. Cache the compiled template (function)

These optimizations improve performance significantly when rendering loops with large amounts of data, but because the with {} statement is abandoned, the outer layer of JSON data must be specified as "data." Prefix, if you think this performance improvement is not important, you can also specify loose:true (loose mode) in options, so that you can omit data. Prefix.

Finally, the Options configuration item is introduced, and the default value of the parameter is on the left.

{

Cache:true/false

Loose:false/true

Errorhandling:true/false

}

Cache defaults to true, that is, whether the same template will be cached by juicer after compilation, that is, if caching is enabled, after the same template is compiled for the first time, in order to reduce the time-consuming and improve performance, the compiled template function will not be executed again but will be fetched directly from the cache.

API of Juicer. There are two ways to use Juicer, one is through the

Juicer.to_html (tpl,data,options)

Convert the template to html code directly according to the data provided. The other is to compile the template first through the compile method, and then perform data Render operation on the template when needed:

Var compiled_tpl=juicer.compile (tpl,options)

Compiled_tpl.render (data)

At this point, I believe that everyone on the "Javascript template engine implementation and optimization" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report