Front-End Engineering: A summary of JavaScript optimizations

Source: Internet
Author: User

I think the optimization of JavaScript is a profound knowledge, here can only stand on the shoulders of predecessors, said some of my superficial understanding, more hope is to throw the jade, if not, please treatise.

First of all, to realize that the key to optimizing JS is to optimize its running speed, as a starting point.

The optimization principle of JavaScript is: 28 principles

  

  Meet the majority of situations, and encounter extreme situations, have the ability to take into account, learn to give up, appropriate trade-offs;

  

  The reason is that one of the factors that affect the user's experience is the response time

    • 0.1s: Users feel very fluent
    • 1.0s: The user's operation may be affected occasionally, and the user can already feel that some is not fluent
    • 10s: The impact on users is more serious, need the corresponding progress tips. Users will also have some frustration (//I think 10s is too broad, usually more than 2s can not stand it)

Of course, JS optimization is only to improve the response time needs improvement aspects of one of the many, front-end optimization knowledge is deep, only in-depth understanding, will be surprised at the front end need to grasp the knowledge is so much, of course, the invisible will give people pressure | | Dynamic. Far away, but still want to recommend two blog about front-end optimization: Front-end engineering to open speed optimization of the progressive summary and web front-end optimization of best practices and tools.

Continue to the subject, OK, then know the goal is to improve response time, speed up the speed of operation, then what are the practical options:

    1. Management scopes
    2. Manipulating data
    3. Flow control
    4. Reflow
    5. DOM Operations
    6. Long-running script processing

  

  

  Management scopes

 Give me a chestnut:

  

var foo = 1;function Test () {//a series of operations on variable foo}function test2 () {var foo = 1;//A series of actions on variable foo}

That is, the local variable exists in the active object, and the parser simply looks for a single object in the scope.

In JavaScript, we should use local variables as much as possible instead of global variables, which everyone knows, but who said the first thing? Why do you do this? What's the basis? If not, how much damage can be done to performance? Here's a excerpt from the JavaScript Variable performance:

  

  One of the most common suggestions for how to improve JavaScript performance is to try to use local variables instead of global variables (globals variables). In my nine years of web development, this advice always lingers in my ear and has never been questioned, and the basis of this advice comes from the way JavaScript handles scopes (scoping) and identifier parsing (identifier resolution).

First, let's make it clear that the function is actually represented as an object in JavaScript, and the process of creating a function is, in fact, the process of creating an object. Each function object has an internal property called [[Scope]] that contains the scope information when the function was created. In fact, the [Scope] property corresponds to a list of objects (Variable Objects), and the objects in the list are accessible from within the function. For example, if we set up a global function A, then A's [[scope]] Internal property contains only one global object, and if we create a new function B in a, then B's [[Scope]] property contains two objects. The activation object for function A is preceded by the global object, which is next.

When a function is executed, it automatically creates an executable object (execution object), and binds to a scope chain (scope Chain) at the same time. The scope chain is established by the following two steps for identifier resolution.

    1. The objects in the internal properties of the function object [[Scope]] are copied sequentially into the scope chain.
    2. Second, when the function executes, a new activation object is created that contains the definition of this, the argument (arguments), the local variable (including named arguments), which activation Object objects are placed at the front of the scope chain.

During the execution of the JavaScript code, when an identifier is encountered, it is searched in the scope chain of the execution context (execution contexts) based on the name of the identifier. Starts from the first object of the scope chain (the function's activation object) and, if it is not found, searches for the next object in the scope chain, and so on, until the definition of the identifier is found. If it is not found after the last object in the scope, that is, the global object, an error is thrown that prompts the user that the variable is undefined (undefined). This is the process of performing model and identifier parsing (Identifier Resolution) of functions described in the ECMA-262 standard, and it turns out that most JavaScript engines do. It is important to note that ECMA-262 does not require the use of this structure, but only describes this part of the function.

Understanding the process of identifier parsing (Identifier Resolution), we can understand why local variables are faster to parse than other variables, mainly because the search process is greatly shortened.

That is, when the process of identifier parsing requires a deep search, it is accompanied by a performance penalty, and the degree of performance loss increases with the depth of the identifier.

  Data manipulation

    1. Using local variables, it is the fastest

Obj.name is faster than obj.xxx.name access, and the speed of accessing the property is related to its depth in the object. “ . ” The number of operations directly affects the time spent accessing object properties.

2. Cache frequently used objects, arrays, and related property values

    

function process (data) {var count = data.count;if (Count > 0) {for (var i = 0; i < count; i++) {ProcessData (data.item[i ]);}}}

3. Do not directly manipulate nodelist, convert it to a static array and then use

Method: Array.prototype.slice.call () + = Standard Browser

Copy to a new array one after another = = for IE

It is important to note that when traversing nodelist, DOM operations that have an effect on the current nodelist-related structures are not done and, as mentioned earlier, cache some frequently used attribute values to avoid unnecessary tragedies. Chestnut:

  

var divs = document.getelementsbytagname (' div ');//Assume that the page has a Div, so divs.length is greater than 0 for (var idx = 0; idx < divs.length; idx + +) {Document.body.appendChild (//Cup with document.createelement (' DIV ')); Console.info (divs.length);}

The above code finally runs the error, cause by constantly inserting the div node into the document.body, the For Loop termination conditions (Div.length also changed) failed, into a dead loop. That is, a reference to a live nodelist is obtained by getElementsByTagName (), and any DOM operations related to it are immediately reflected on this nodelist.

  

  DOM Operations

1. Additions and deletions to check and change

    • Try to use DocumentFragment
    • You can use CloneNode () to replicate a copy of the node when processing it
    • To make a direct modification to the DOM, display:none it first;

2. Specify the context of the operating DOM

  context. getElementsByTagName ()

3. Split method, a way to solve one thing

Split function, let a method do only one thing, by constantly calling methods to implement complex functions, but these simple methods to avoid cross-call each other.

  Be Lazy (causes the script to run as little as possible or not to run.) )  

    1. Short-circuit expression applications: such as a && B | | C
    2. To write the corresponding processing method based on the event
    3. Lazy function

  

  Flow control

  

if (...) {}elseif (...) {}elseif (...) {}elseif (...) {}elseif (...) {}elseif (...) {}else{}

Principle:

    1. In the If statement, place the condition that will often occur, put it in the upper position
    2. If the condition of a continuous interval, you can use the method of dichotomy to split
    3. More discrete values, you can use switch to replace
    4. How to use array queries
    5. Be aware of implicit type conversions
    6. Be careful with recursion.  
var foo = 0;    if (foo = = false) {//Implicit conversion ...     

  

function Recurse () {recurse ();} Recurse (); Again a tragedy, will error, infinite recursion

  

  Reflow

What is reflow, that is: there is a concept of rendering objects in the CSS specification, usually represented by a box (box, rectangle).    Mozilla operates the box with an object called frame. There are three main actions of frame:

    • Constructs a frame to create an object Tree (DOM tree)
    • Reflow to determine the object location, or to call Mozilla's layout (this refers to the implementation of the source code)
    • Draw so that the object can be displayed on the screen

In general, Reflow is a process of loading a content tree (which is the DOM tree in HTML) and a response to creating or updating a frame structure.

The causes of Reflow are:

    • Manipulating the DOM tree
    • Layout-related style changes
    • Change classname
    • Window resizing
    • The size of the word Hugh

Therefore, in order to improve the performance of the page, it is to avoid reflow overhead.

  

Front-End Engineering: A summary of JavaScript optimizations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.