Home  >  Article  >  Web Front-end  >  JavaScript code specifications and performance finishing

JavaScript code specifications and performance finishing

大家讲道理
大家讲道理Original
2017-03-04 15:11:541385browse
  1. Performance

There are many things to pay attention to in terms of performance of Js:

  • Avoid global lookup

The most important thing to optimize Js performance is to pay attention to the global search, because the scope search is to first search the local scope, and then go to the upper level scope to search until the global scope is not found, so the performance consumption of the global scope search must be higher than The local scope of this function consumes a lot of money. for example:

function setInnerHtml(){  var pDom=doucument.getElementsByTagName(“p”);  for(var i=0,len=pDom.lemgth;i<len;i++){

    pDom.innerHTML=doucument.getElementByid(“dom”).innerHtml+I;

}

}

This code calls document.getElementByid("dom") in a loop, and the document is only executed once outside the loop, so there is no need to assign the document to a local variable. Instead, assign the value inside the loop to a local variable, so there is no need to re-enter the loop each time. To find the global document object.

function setInnerHtml(){  var domhtml= doucument.getElementByid(“dom”).innerHtml;  var pDom=doucument.getElementsByTagName(“p”);  for(var i=0,len=pDom.lemgth;i<len;i++){

    pDom.innerHTML= domhtml +I;

}

}

The principle is that when the global object is called multiple times, especially in a loop, the global object is finally assigned to the local variable. Of course, the performance difference will not be obvious after dozens of calls, but as a programmer, since Performance-optimized writing should be done as much as possible.

  • Avoid with statements

This statement is rarely used nowadays, so I won’t say more about it.

  • Avoid unnecessary attribute lookups

To put it simply, the variable stores the value. The performance consumption of calling this variable is minimal, while the performance consumption of taking the value of the object's attribute is relatively high. for example:

var query=window.location.href.subtring(window.location.href.indexOf(“?”));

This code has 6 attribute searches that are particularly inefficient. It is best to change it to:

var url=window.loaction.href;var query=url.substring(url.indexOf(“?”));

This optimization improves the efficiency a lot.

  • optimization loop

1) Decrease iteration: Most loops start from 0 and increase the loop. In many cases, it is more efficient to decrease the loop from the maximum value.

2) Simplify the termination conditions: Since the termination conditions will be judged every time it loops, simplifying the termination conditions can also improve loop efficiency.

3) Simplify the loop body: The loop body is the most executed, so the optimization of the loop body must be ensured.

  • Avoid parsing js code string

When parsing js code strings in js code, a parser must be restarted to parse the code, which causes relatively large performance consumption, so try to avoid functions such as eval and function constructing js code words.

String function, when setTimeout passes a string.

  • The native method is faster, so try to use the native method.

  • Switch statement is faster.

  • Bitwise operators are faster.

2. Code specifications

  • Code comments:

1) Functions and methods: Each function or method should contain comments describing the function, input and output of the function.

2) Complex algorithms: Comments should be added to complex algorithms so that people can understand the logical thinking of the algorithm.

3) Hack: Comments should also be added to the compatibility code.

4) Large blocks of code: Multiple lines of code used to complete a single task should be preceded by a comment describing the task.

  • Decoupling HTML/JavaScript

Html is the structure, and js is the behavioral layer. They inherently need to interact. When we write code, we should try to reduce the correlation between html and js. Some methods will make them too tightly coupled, such as: js in the html page Declaring js code in the script tag, binding onclick events in the html tag, and rewriting the html code in js will cause HTML and js to be too tightly coupled.

Html rendering should be kept separate from js as much as possible. When js is used to insert data, try not to insert tags directly. Generally, you can directly include and hide tags in the page, and then wait until the entire page is rendered, and then use js to display the tag. .

将html和js解耦可以在调试过程中节省时间,更加容易确定错误的来源,也减轻维护难度。

  • 解耦css/JavaScript

JavaScript和css也是非常紧密相关的,js经常对页面的样式做动态修改。为了让他们的耦合更松散,可以通过js修改对应的class样式类。

  • 解耦应用逻辑/事件处理程序

在实际开发中我们经常在一个事件函数出来将要处理的所有代码都放在这个事件中,例如:

function handleKeyPress(event){

   event=EventUtil.getTarget(event);   if(event.keyCode===13){var target=EventUtil.getTarget(event);var value=5*parseInt(target.value);if(value>10){

 document.getElementById(“error-msg”).style.display=”block”;

}

}

}

 

这里就是把逻辑处理代码和事件处理代码放到一起,这样会让调试不好调试,维护难度变高,而且要是突然修改要新增加一个事件做同样类似的逻辑处理,那就要复制一份逻辑处理代码到另一个事件函数中。较好的方法是将应用逻辑和事件处理程序分离开。例如:

function validateValue(value){

 value=5*parseInt(value); if(value>10){

 document.getElementById(“error-msg”).style.display=”block”;

}

}function handleKeyPress(event){

  event=EventUtil.getEvent(event);  if(event.keyCode===13){   var target=EventUtil.getTarget(event);

   validateValue(target.value);

}

}

 

这样事件处理和逻辑处理就分离开了,这样做有几个好处,可以让你更容易更改触发特定过程的事件,其次可以在不附加到事件的情况下测试代码,使其更易创建单元测试或是自动化应用流程。

事件和应用逻辑之间的松散耦合的几条原则:

  1. 勿将event对象传给其他方法;只传来着event对象中所需要的数据;

  2. 任何可以在应用层面的动作都应该可以在不执行任何时间处理程序的情况下能正常运行。

  3. 任何时间处理程序都应该处理事件,然后将处理转交给应用逻辑。

  • 避免全局变量

这样会让脚本执行一致和可维护,最多创建一个全局变量。类似jQuery一样,所以方法属性都在$对象当中,避免对全局变量造成过多的污染。

  • 尽量使用常量

数据和使用它的逻辑进行分离要注意一下几点:

  1.  重复值

  2. 用户界面字符串

  3.  url

  4. 任意可能会更改的值

  • 其他优化

  1. 多变量声明时用一条语句逗号隔开声明

  2. 对dom的操作的优化

  3. 对dom进行html代码插入尽量在最后一次添加到dom对象中。

  4. innerHTML的效率要比appendChild的效率高,以为innerHTML会创建一个HTML解析器,然后使用内部的DOM调用来创建DOM结构,而非基于JavaScript的DOM调用,由于内部方法是编译好的而非解释执行,所以执行快的多。

  5. 使用事件委托减少绑定的事件数量。

  6. 尽量少用到返回HTMLCollection语句。

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