Knowledge about how to effectively improve JavaScript execution efficiency and javascript Execution Efficiency

Source: Internet
Author: User
Tags website performance

Knowledge about how to effectively improve JavaScript execution efficiency and javascript Execution Efficiency

To provide a fresh and unique user experience, many websites use JavaScript to improve design, verify forms, check browsers, Ajax requests, cookie operations, and so on, to achieve a refreshing and dynamic effect. However, to present a large amount of content in the browser, if not handled well, the website performance will drop sharply. Therefore, we need to know how to improve the efficiency of JavaScript Execution.

JavaScript Functions

In JavaScript, functions are pre-compiled before use. Although strings can be used to replace functions in some cases, every time you execute this JavaScript code, it will be parsed again, affecting performance.

1. eval example
Copy codeThe Code is as follows:
Eval ('output = (input * input )');
// We recommend that you change it:
Eval (new function () {output = (input * input )});

2. Example of setTimeout

Copy codeThe Code is as follows:
SetTimeout ("alert (1)", 1000 );
// We recommend that you change it:
SetTimeout (function () {alert (1)}, 1000 );

Use functions instead of strings as parameters to ensure that the code in the new method can be optimized by the JavaScript compiler.

JavaScript Scope

Each scope in the JavaScript scope chain contains several variables. It is important to understand the scope chain so that it can be used.

Copy codeThe Code is as follows:
Var localVar = "global"; // global variable

Function test (){

Var localVar = "local"; // local variable

// Local variable
Alert (localVar );

// Global variable
Alert (this. localVar );

// Search for the global variable if the document cannot be found in the local variable
Var pageName = document. getElementById ("pageName ");
}

Using local variables is much faster than using global variables, because the longer the scope chain, the slower the resolution. The scope chain structure is displayed:

If the Code contains a with or try-catch statement, the scope chain is more complex, such:

JavaScript string

A function in JavaScript that has a major impact on performance is a string connection. Generally, the + number is used to concatenate strings. However, in the early days, browsers did not optimize such connection methods, resulting in the continuous creation and destruction of strings seriously reducing the JavaScript execution efficiency.

Copy codeThe Code is as follows:
Var txt = "hello" + "" + "world ";

We recommend that you change it:

Copy codeThe Code is as follows:
Var o = [];
O. push ("hello ");
O. push ("");
O. push ("world ");
Var txt = o. join ();

Let's simply encapsulate the following:

Copy codeThe Code is as follows:
Function StringBuffer (str ){
Var arr = [];
Arr. push (str | "");
This. append = function (str ){
Arr. push (str );
Return this;
};
This. toString = function (){
Return arr. join ("");
};
};

Then, call:

Copy codeThe Code is as follows:
Var txt = new StringBuffer ();
Txt. append ("Hello ");
Txt. append ("");
Txt. append ("World ");
Alert (txt. toString ());

JavaScript DOM operations

The HTML Document Object Model (DOM) defines standard methods for accessing and operating HTML documents. It represents an HTML document as a node tree that contains elements, attributes, and text content. By using html dom, JavaScript can access all nodes in the HTML document and operate on them.

DOM re-painting

Each modification to the DOM object on the page involves DOM re-painting, and the browser will re-render the page. Therefore, reducing the number of DOM object modifications can effectively improve JavaScript performance.

Copy codeThe Code is as follows:
For (var I = 0; I <1000; I ++ ){
Var elmt = document. createElement ('P ');
Elmt. innerHTML = I;
Document. body. appendChild (elmt );
}

We recommend that you change it:

Copy codeThe Code is as follows:
Var html = [];
For (var I = 0; I <1000; I ++ ){
Html. push ('<p>' + I + '</p> ');
}
Document. body. innerHTML = html. join ('');

DOM access

You can use DOM to access every node in the HTML document. Every time you call methods such as getElementById () and getElementsByTagName (), the node will be searched and accessed again. Therefore, caching the searched DOM node can also improve the JavaScript performance.
Copy codeThe Code is as follows:
Document. getElementById ("p2"). style. color = "blue ";
Document. getElementById ("p2"). style. fontFamily = "Arial ";
Document. getElementById ("p2"). style. fontSize = "larger ";

We recommend that you change it:

Copy codeThe Code is as follows:
Var elmt = document. getElementById ("p2 ");
Elmt. style. color = "blue ";
Elmt. style. fontFamily = "Arial ";
Elmt. style. fontSize = "larger ";

DOM Traversal

DOM traversal sub-elements are usually used to read the next sub-element cyclically by index. In earlier browsers, this reading method is very inefficient. nextSibling can be used to improve the efficiency of js DOM traversal.

Copy codeThe Code is as follows:
Var html = [];
Var x = document. getElementsByTagName ("p"); // All nodes
For (var I = 0; I <x. length; I ++ ){
// Todo
}

We recommend that you change it:

Copy codeThe Code is as follows:
Var html = [];
Var x = document. getElementById ("div"); // The parent node
Var node = x. firstChild;
While (node! = Null ){
// Todo
Node = node. nextSibling;
}

JavaScript Memory release

In web applications, memory consumption increases as the number of DOM objects increases. Therefore, the reference of the object should be released in time so that the browser can recycle the memory.

Releases the memory occupied by the DOM.

Copy codeThe Code is as follows:
Document. getElementById ("test"). innerHTML = "";

Set innerHTML of the DOM element to an empty string to release the memory occupied by its child elements.

Release javascript objects

Copy codeThe Code is as follows:
// Object:
Obj = null
// Object attributes:
Delete obj. property
// Array element:
Arr. splice (); // Delete the first three elements

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.