Performance optimization tips for JavaScript

Source: Internet
Author: User
Tags script tag

When it comes to JavaScript performance optimizations, there are a number of points, such as putting the script near the body close tag, merging multiple script tags, and so on, and some code performance that is not as good as the performance of while, using while to simulate for loops, and so on.

1. Starting from load

In the browser, the execution and download of JS file will block the rendering of CSS and DOM, which is caused by the browser's single thread, and later CHROME,FF and other browsers have enabled the
JS file parallel Download, however JS file operation will still be blocked, and some browsers support defer keyword.

<Scripttype= "Text/javascript"defer>Alert ("defer");</Script><Scripttype= "Text/javascript">Alert ("OK")</Script><Scripttype= "Text/javascript">window.onload=function() {alert ("onload"); }</Script>

Browsers that do not support defer will output defer,ok,onload, and the support will pop up Ok,defer and Onload,defer before the DOM is rendered.
JS file can also be the script tag with JS dynamic loading. This way, the download execution of the file does not affect the process of other pages.

In addition, you can listen to the script tag load event, while IE triggers a readystatechange event, and there is a readystate,
It has 5 states, the most important is the loaded and complete events, however, the two events of IE are inconsistent, and sometimes loaded events do not complete, and sometimes vice versa.
Then we can judge at the same time when we use it:

var script=document.createelement ("script"); Script.type= "Text/javascript"; Script.onreadystatechange=function() {    if (script.readystate== "Loaded" | | script.readystate== "complete") {        Script.onreadystatechange=null;   to prevent event handling two times        alert ("Script OK");    } Script.src= "file.js";d ocument.body.append (script);

2. Optimization of data storage

If the external data is used more than once within the scope of the function, it is best to use a local variable, because the local variable has the least performance consumption within the scope of the function.
Local variables are preferred in the function scope chain, and the performance consumption of global variables is relatively high.

var a=doucument.getelementbyid ("AA");d ocument.body.onclick=function() {     var temp=A;     // temp To do something ...            }

Optimization of 3.dom operation

A collection of Dom that exists in JavaScript, such as document.getElementsByTagName ('), document.links,document.images,document.forms,
Document.forms[0].elements, they are all class arrays, have a length property, and when they traverse, they look for calculations again, and putting them in a real array is an optimization scheme.
Or you can use length as a variable to represent it;

var col=document.getelementsbytagname (' div '); var len=col.length;  for (var i = 0; i < len; i++) {    //todo;};

In the structure of the DOM selection, firstchild,nextsibling,previoussibling contains both text nodes and annotation nodes, for example, in the selection Dom I wrote before, I wrote several nextSibling. When selecting sub-elements, nextsibling is more economical than childnodes performance, saving more performance in IE, and jquery children is also used nextsibling selected.
The following structure, IMG1 nextsibling is a text node, if you filter the words will produce performance consumption, modern browser provides nextelementsibling,previouselementsibling and so on, They can automatically filter text nodes and annotation nodes to improve performance,
ie6,7,8 only supports children.

<src= ""  ID= "IMG1"><!--   - <  src= ""  ID= "Img2">

In the DOM selection, Queryselectorall has better properties than getElementById, such as in this structure:

var b=document.queryselectorall (' Img#img1,img#img2 ');

Queryselectorall is more convenient, but the performance of the loop iterative getElementById is not very good. Browser support is the right use.

Optimization of 4.for Cycles

For loop optimization, more than 1000 iterations, with Duff devices faster, the basic idea is to use while instead of for. And the foreach is slower than the For loop;
If else and switch, it is also a performance consideration to use the if else with the switch condition when there are many conditions.
Recursive optimization, you can turn recursion into an iteration. In order to prevent recursive doing some repetitive calculations, you can set up a cache as follows, depending on the actual situation of choice. Called watchmaking technology. Here is an example of a watchmaking technique:

function Merta (n) {    if (!  Merta.cache) {        Merta.cache={            0:0,            1:1        }    };     if (! merta.cache.hasOwnProperty (n)) {        Merta.cache[n]=n*merta (n-1);    };     return merta.cache[n];}

To calculate the factorial of the number, each recursive result is buffered, thereby achieving performance savings.

5. Optimization of strings

str+= "one" + "one";

When running, a temporary variable = "Onetwo" is generated, and then the temporary variable is +=str, and str=str+ ' one ' + ' one ' will prevent the temporary variable from being generated, thus optimizing. In most browsers will speed up 10%-40%

In IE, these optimizations do not apply, IE's string processing mechanism is not used, in IE8 the connection string will only note the individual strings of the reference, at the time of the connection, the individual strings are copied into the real string, and replace its reference.
But IE8 's previous implementations are worse, and this approach will make it more efficient. IE8 used to allocate space for each copy of a string, and the performance consumption multiplied when a large number of strings were concatenated, and could only be optimized using the array connection method.

 while (len--) {    newstr[newstr.length]=str;} Newstr=newstr.join (");

Performance optimization tips for JavaScript

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.