JavaScript front-end performance optimization tips instances Summary

In many languages, JavaScript has occupied an important place, the use of JavaScript we can do a lot of things, a wide range of applications.

In a web application project, requires a lot of JavaScript code, the future will be more and more.

However, due to JavaScript as a language is interpreted, and its single-threaded mechanism to determine the performance problem is the weakness of JavaScript, a developer in question is also the time to write JavaScript must be noted.

Often encounter problems because of poor performance of Web 2.0 applications, the main reason is the lack of JavaScript performance, cause the browser to overload. Javascript performance optimization by no means a written skills, then how should the right to load and execute JavaScript code to improve its performance in the browser it? Here we give the knowledge to do some optimization tips summary.

Regardless of the current JavaScript code is embedded in the outer chain or file, the page download and rendering must stop and wait for the script execution is complete. JavaScript execution process takes longer, the longer it waits for the browser in response to user input. He was made a few years old codes of agricultural development, I recommend learning of front-end development buckle qun 767273102, whether you are big or small white cow, or would want to switch into the line can come together to learn to understand progress together! There are development tools, a lot of dry goods and technical information to share! I hope the novice detours

The reason appears blocked browser when downloading and executing the script that the script may change the namespace pages or JavaScript, and they will have an impact later in the page content. A typical example is the use of the page:

document.write() 

Example:

<html><head> 
 <title>Source Example</title></head><body> 
 <p> 
 <script type="text/javascript"> 
 document.write("Today is " + (new Date()).toDateString()); </script> 
 </p></body></html> 

When the browser encounters a <script> tag, no way to know whether the current HTML page JavaScript can add content to the <p> tag, or introduce other elements, or even to remove the label.

Therefore, when the browser stops processing pages, execute JavaScript code, and then continue parsing and rendering the page.

The same situation also occurred in the course of using the src attribute to load JavaScript, the browser must first take the time to download the code outside the chain file, then parse and execute it. In this process, the page rendering and user interaction completely blocked.

Do not use with () statement

This is because with () statement will add additional variables at the beginning of the scope chain. Additional variables means that, when any variable that needs to be accessed, JavaScript engines need to scan with () statement variables generated, and then the local variable, and finally the global variables.

So with () statement at the same time have a negative impact on the performance of local variables and global variables, eventually we plan to optimize the performance of JavaScript bankruptcy.

Object properties and array elements than the variable speed slow

Speaking JavaScript data, in general, there are four kinds of access methods: the value, variable, object properties and array elements. When considering optimization, similar performance numbers and variables, and the speed of object properties and significantly better than the array elements.

So many times when you refer to an object property or array element, you can get a performance boost by defining variable. (This is a read, write valid data) While this rule is correct in most cases, but Firefox has done some interesting work on the optimization of the array index, we can make it better than the actual performance variables.

But given the performance of the array elements drawbacks on other browsers, or should try to avoid the array to find, unless you really only for the performance of Firefox and development.

Avoid Global Search

Speed ​​function will be used in a global object is stored as a local variable to reduce global find, because the speed of access to the local variables than global variables faster access

function search() {  
 //当我要使用当前页面地址和主机域名 
 alert(window.location.href + window.location.host); 
 }  
 //最好的方式是如下这样 先用一个简单变量保存起来 
 function search() {  
 var location = window.location; 
 alert(location.href + location.host); 
 } 

Avoid the with statement

And similar functions, with statement creates its own scope, thus increasing the length of scope chain execution code which, due to the scope chain to find additional, code execution with the statement in the code would surely be performed outside slowly, try not to use the with statement when not in use with energy statement.

with (a.b.c.d) { 
 property1 = 1; 
 property2 = 2; 
 } //可以替换为: 
 var obj = a.b.c.d; 
 obj.property1 = 1; 
 obj.property2 = 2; 

Digital converter to a string

Generally best to use "" + 1 to convert a number to a string, though it looks a little ugly, but in fact this is the highest efficiency, performance and said:

(“” +) > String() > .toString() > new String() 

By template element clone, replace createElement

Many people like to use document.write to generate content to the page in JavaScript. In fact this low efficiency, if you need directly into the HTML, you can find a container element, such as specifying a div or span, and set their innerHTML to be your own HTML code into the page.

Normally we might use to write HTML directly to create a string node, in fact, to do so, 1: can not guarantee the validity of the code, 2: Low string manipulation efficiency, so it should be used document.createElement () method, and if the document after the existence of ready-made model node should be using cloneNode () method, because using createElement () method, you need to set the properties of multiple elements, use cloneNode () to set the number of properties can be reduced - if you need to create a lot of the same elements , you should first prepare a model node.

var frag = document.createDocumentFragment();  
 for (var i = 0; i < 1000; i++) {  
 var el = document.createElement('p'); 
 el.innerHTML = i; 
 frag.appendChild(el); 
 } document.body.appendChild(frag);  
 //替换为: 
 var frag = document.createDocumentFragment(); var pEl = document.getElementsByTagName('p')[0];  
 for (var i = 0; i < 1000; i++) {  
 var el = pEl.cloneNode(false); 
 el.innerHTML = i; 
 frag.appendChild(el); 
 } document.body.appendChild(frag); 

Avoid inefficient script location

HTML 4 specification states that <script> tag may be placed <head> or <body> HTML document, and allows multiple occurrences. Web developers typically JavaScript diet loading in the chain of the <head>, followed by <link> tag is used to load the chain CSS files or other information pages.

Inefficient script location Example:

<html><head> 
 <title>Source Example</title> 
 <script type="text/javascript" src="script1.js"></script> 
 <script type="text/javascript" src="script2.js"></script> 
 <script type="text/javascript" src="script3.js"></script> 
 <link rel="stylesheet" type="text/css" href="styles.css"></head><body> 
 <p>Hello world!</p></body></html> 

However, this conventional approach conceals serious performance problems.

In the example in Listing 2, when the browser parses the <script> tag when (line 4), the browser will stop parsing subsequent content, priority download the script file and executes the code, which means that after styles.css style file and <body> tag can not be loaded, because the <body> tag can not be loaded, naturally, can not render the page.

Therefore, before the implementation of the JavaScript code is completely finished, the pages are blank. The following diagram depicts the download page load the script and style documents.

JavaScript front-end performance optimization tips instances Summary

We can find an interesting phenomenon: the first JavaScript file to start the download, at the same time blocking the download page for other files.

In addition, to complete script1.js download from script2.js there is a delay before the download starts, this time happens to be the implementation process script1.js file. Each file must be downloaded and executed to complete the download will not begin until the previous file. In these documents one by one during the download, the user sees is a blank page.

From IE 8, Firefox 3.5, Safari 4 and Chrome 2 starts allow JavaScript file parallel download. This is good news, because the <script> tag when downloading external resources will not block other <script> tag. Unfortunately, JavaScript will block the download process is still downloading other resources, such as style files and pictures.

Although the script of the download process will not affect each other, but the page still have to wait for all the JavaScript code is downloaded and executed before continuing. Thus, while the latest browser by allowing parallel downloading improves performance, but the problem has not been fully resolved, script blocking remains a problem.

Since the script page to download other resources obstruction, it is recommended that all <script> tags into the bottom of the <body> tag as possible to minimize the impact on the entire page to download.

Recommended placement sample code:

<head> 
 <title>Source Example</title> 
 <link rel="stylesheet" type="text/css" href="styles.css"></head><body> 
 <p>Hello world!</p> 
 <!-- Example of efficient script positioning --> 
 <script type="text/javascript" src="script1.js"></script> 
 <script type="text/javascript" src="script2.js"></script> 
 <script type="text/javascript" src="script3.js"></script></body></html> 

This code shows the recommended location to place <script> tags in the HTML document. Although the script will block downloads another script, but most of the contents of the page have the download is complete and displayed to the user, so the page does not download too slow.

This is the first rule of optimization JavaScript: the script at the bottom.

Carefully use a closure

Although you may not know "closure", but you can often use this technique inadvertently. Closures are essentially regarded JavaScript in new, when we define a real-time function, we use closures, such as:

document.getElementById('foo').onclick = function(ev) { }; 

Closure problem is that: by definition, have in their scope chain at least three objects: closure variables, local variables and global variables. These additional objects will cause other performance issues. But Nicholas does not want us to be unworthy, the closure is still very useful to improve code readability and other aspects, but do not abuse them (especially in the cycle).

When the loop control variable control conditions, and merged

Mentioned performance, the need to avoid the cycle of work has been a hot topic since the implementation of the cycle will be repeated many times. So if there is a demand for performance optimization, circulation prior to surgery may get the most significant performance gains.

A method for optimizing cycle is defined cycle time, the control condition and control variables combined, the following is an example not to combine them:

for ( var x = 0; x < 10; x++ ) { 
}; 

Before we want to add something to this cycle, we find that there are several that appear in each iteration. JavaScript engine needs:

#1:检查 x 是否存在#2:检查 x 是否小于 0 <span style="color: #888888;">(这里可能有笔误)</span>#3:使 x 增加 1

However, if you are just some of the elements of iterations elements, then you can use while cycle rotation to replace above this operation:

var x = 9;do { } while( x-- ); 

Using XMLHttpRequest (XHR) objects

This technology was first to create a XHR object, and then download the JavaScript file, followed by a dynamic <script> element will inject JavaScript code page.

JavaScript enabled via XHR object:

var xhr = new XMLHttpRequest(); 
xhr.open("get", "script1.js", true); 
xhr.onreadystatechange = function(){  
 if (xhr.readyState == 4){  
 if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){  
 var script = document.createElement ("script"); 
 script.type = "text/javascript"; 
 script.text = xhr.responseText; document.body.appendChild(script); 
 } 
 } 
}; 
xhr.send(null); 

This code sends a GET request to a server script1.js file. onreadystatechange event handler checks readyState is not 4, then check the HTTP status code is not valid (2XX indicates valid response 304 represents a cached response).

If a valid response is received, then create a new <script> element, it is arranged to receive text attributes from the server responseText string.

Doing so will actually create a <script> element with inline code. Once the new <script> element is added to the document, the code will be executed, and ready to use.

The main advantage of this method is that you can download the JavaScript code is not executed immediately. Since the code is returned outside the <script> tag (in other words not <script> tag constraints), after it will not download automatically, which allows you to postpone the execution until everything is ready.

Another advantage is that the same code will not throw an exception in all modern browsers.

The main limitation of this method is: JavaScript file must be placed in the same page with the region, can not be downloaded from the CDN (CDN referred to as "content delivery network (Content Delivery Network)", so a large web page is not normally used XHR script injection technology.

Note NodeList

Minimize the number of access NodeList performance can be greatly improved script

var images = document.getElementsByTagName('img'); for (var i = 0, len = images.length;  
i < len; i++) { 
 } 

When writing JavaScript must be aware of when to return NodeList object, which can minimize access to them.

1, that the call to getElementsByTagName () of

2, get the childNodes attribute element

3, attributes acquired properties of the elements

4, access to special collections, such as document.forms, document.images etc.

To understand when using NodeList objects, greatly enhancing the rational use of code execution speed

Avoid compared with null

Because JavaScript is loosely typed, so it does not do any automatic type checking, so if you see code compared with null, try the following techniques to replace:

1, if the reference value should be a type using ××× tanceof operator checks its constructor

2, if the value type is to be checked typeof a basic type, effect

3, if you want the object that contains the name of a particular method, use the typeof operator to ensure that the specified method name exists on the subject

Respect of the ownership of Object

Because JavaScript can be modified at any time by any object, so that you can be unpredictable way override the default behavior, so if you are not responsible for maintaining an object, its object or its methods, then you do not modify it , specific point to say:

1, do not add a property as an example or prototype

2, not as an example a method of adding or prototype

3, do not redefine an existing method

4. Do not repeat the definition of a method other team members have realized, never modify not, you can create a new function of all of your objects as objects in the following ways:

01, create a new object that contains the desired function, and interact with the objects associated with it

02, create custom types, inheritance need to modify the type, and can customize the type of additional functionality

Circular references

If a circular reference contains DOM object or ActiveX objects, a memory leak occurs.

The consequences of a memory leak is before the browser is closed, even if the page is refreshed, this memory will not be released browser.

Simple circular reference:

var el = document.getElementById('MyElement');  
 var func = function () {  
 //… 
 } 
 el.func = func; 
 func.element = el; 

But this usually does not happen. Typically occurs in a circular reference added closure element is as expendo dom time.

function init() {  
var el = document.getElementById('MyElement'); 
el.onclick = function () {  
//…… 
} 
} 
init(); 

init in the implementation of the current context we call context. This time, context quoted el, el cited function, function references context. This time the formation of a circular reference.

The following two methods can solve circular references:

1, the object blanking dom

function init() {  
 var el = document.getElementById('MyElement'); 
 el.onclick = function () {  
 //…… 
 } 
 } 
 init();  
 //可以替换为: 
 function init() {  
 var el = document.getElementById('MyElement'); 
 el.onclick = function () {  
 //…… 
 } 
 el = null; 
 } 
 init(); 

The blanking el, context dom does not contain a reference to the object, thereby interrupt the cycle applications.

If we need to dom object returned, you can use the following method:

function init() {  
 var el = document.getElementById('MyElement'); 
 el.onclick = function () {  
 //…… 
 } return el; 
 } 
 init();  
 //可以替换为: 
 function init() {  
 var el = document.getElementById('MyElement'); 
 el.onclick = function () {  
 //…… 
 } try {  
 return el; 
 } finally { 
 el = null; 
 } 
 } 
 init(); 

2, construct a new context

function init() {  
 var el = document.getElementById('MyElement'); 
 el.onclick = function () {  
 //…… 
 } 
 } 
 init();  
 //可以替换为: 
 function elClickHandler() {  
 //…… 
 } function init() { var el = document.getElementById('MyElement'); 
 el.onclick = elClickHandler; 
 } 
 init(); 

The function pumped new context, so that, the function of the context does not contain references el, thereby interrupting circular reference.

By dom javascript object is created, you must append to the page

Under IE, dom objects created by the script, if not append to the page, refresh the page, this memory is not recovered!

 function create() {  
 var gc = document.getElementById('GC'); for (var i = 0; i < 5000; i++) {  
 var el = document.createElement('div'); 
 el.innerHTML = "test";  
 //下面这句可以注释掉, 
看看浏览器在任务管理器中, 
点击按钮然后刷新后的内存变化 
 gc.appendChild(el); 
 } 
 } 

String concatenation

To connect the plurality of strings, the + = should be less, such as

s+=a;  
s+=b;  
s+=c; 

Should be written

s+=a + b + c; 

If the string is collected, such as a multiple of the same string + = operator, it is preferable to use a buffer, using JavaScript array to collect the last join connecting method using

var buf = []; 
 for (var i = 0; i < 100; i++) { buf.push(i.toString()); 
 } var all = buf.join(""); 

Various types of conversion

var myVar = "3.14159", 
 str = "" + myVar, // to string  
 i_int = ~ ~myVar, // to integer  
 f_float = 1 * myVar, // to float  
 b_bool = !!myVar, /* to boolean - any string with length  
 and any number except 0 are true */ 
 array = [myVar]; // to array 

If a defined toString () method for type conversion, then recommend  explicitly call toString ()  , because the internal operation after trying all possibilities, will try to object toString () method attempts can be transformed into String, so a direct call this method will be more efficient.

More type declaration

All variables in JavaScript can use a single var statement to declare, so that combined statement, in order to reduce the execution time of the entire script, just as the same as the above code, the above code format is also very standard, makes one look clear.

Insert iterator

The var name = values ​​[i]; i ++; two preceding statements can be written as var name = values ​​[i ++].

Direct amount

var aTest = new Array(); //替换为 
 var aTest = []; 
 var aTest = new Object; //替换为 
 var aTest = {}; 
 var reg = new RegExp(); //替换为 
 var reg = /../; 
 //如果要创建具有一些特性的一般对象,也可以使用字面量,如下: 
 var oFruit = new O; 
 oFruit.color = "red"; 
 oFruit.name = "apple"; 
 //前面的代码可用对象字面量来改写成这样: 
 var oFruit = { color: "red", name: "apple" }; 

Avoidance of double interpretation

If you want to improve code performance, as much as possible to avoid the need to follow a string of JavaScript interpreter appears, that is,

1, minimize the use of eval function

Use equivalent to calling eval at runtime engine to explain the content to run again, you need to consume a lot of time, and the use of safety problems caused by Eval can not be ignored.

2, do not use the Function constructor

Do not pass a string parameter setTimeout or setInterval

var num = 0; 
setTimeout('num++', 10); 
//可以替换为: 
var num = 0; 
function addNum() { 
num++; 
} 
setTimeout(addNum, 10); 

Shorten negative detection

if (oTest != '#ff0000') { 
 //do something 
 } 
 if (oTest != null) { 
 //do something 
 } 
 if (oTest != false) { 
 //do something 
 } 
 //虽然这些都正确,但用逻辑非操作符来操作也有同样的效果: 
 if (!oTest) { 
 //do something 
 } 

Release javascript object

In rich applications, with the increase in the number of objects instantiated, memory consumption will keep rising. So shall promptly release the reference to the object, so that these can be recovered GC controls memory.

Object: obj = null

Object Properties: delete obj.myproperty

Array item: splice method using an array of arrays do not release the item

Performance Considerations

1, make use of native methods

2, switch statements if relatively fast

By the case statement is organized according to the most likely to least likely of the order.

3, bit operation faster

When performing digital operation, bit Boolean operators or any arithmetic operation faster than arithmetic.

4. Using Boolean operators && and ||

function eventHandler(e) { 
 if (!e) e = window.event; 
 } 
 //可以替换为: 
 function eventHandler(e) { 
 e = e || window.event; 
 } 
 if (myobj) { 
 doSomething(myobj); 
 } 
 //可以替换为: 
 myobj && doSomething(myobj); 

Attention to avoid the wrong place

1, at the end of each statement to be added semicolon

If statement, the conditional expression even if only one statement also with {} enclose it, in order to avoid subsequent logic errors caused if added after the statement.

2, need to be cautious when using the +

JavaScript and various other programming languages, in JavaScript, '+' denotes the digital values ​​are added in addition to, other than the connecting string, may also be used as a unary operator, the string is converted to digital. Therefore, if used improperly, the operator may increase from the '+' confusion caused by calculation errors.

var valueA = 20; 
 var valueB = "10"; 
 alert(valueA + valueB); //ouput: 2010  
 alert(valueA + (+valueB)); //output: 30  
 alert(valueA + +valueB); //output:30  
 alert(valueA ++ valueB); //Compile error 

3, using the return statement note

A return to the values ​​of the return statement do not use () parentheses to enclose the return value, if the return expression, the expression should return when the keywords on the same line, in order to avoid compression, compression tool automatically returns caused by a semicolon developers inconsistent results.

function F1() { 
 var valueA = 1; 
 var valueB = 2; 
 return valueA + valueB; 
 } 
 function F2() { 
 var valueA = 1; 
 var valueB = 2; 
 return 
 valueA + valueB; 
 } 
 alert(F1()); //output: 3  
 alert(F2()); //ouput: undefined 

The difference between == and ===

Conditions to avoid assignment of the part if and while statements, such as if (a = b), should be written if (a == b), but in case of equality comparison is preferably used to run congruent character, i.e. using === and! == operator will respect == and! = good point. == and! = Operators will be typecast.

var valueA = "1"; 
 var valueB = 1; 
 if (valueA == valueB) { 
 alert("Equal"); 
 } 
 else { 
 alert("Not equal"); 
 } 
 //output: "Equal" 
 if (valueA === valueB) { 
 alert("Equal"); 
 } 
 else { 
 alert("Not equal"); 
 } 
 //output: "Not equal" 

Do not use raw partial syntax

Do not use raw partial grammar, write confusing code, although able to correctly identify the computer and run, but after the obscure code is not convenient to maintain.

The function returns the type of unity

Although JavaScript is weakly typed, it is a function of the foregoing return the integer data type, returns a Boolean value later compiled and run through can be normal, but in order to regulate the future maintenance and ease of understanding, should ensure that the function should return a unified data type .

Always check the data types

To check all the data you input methods, one is for security, on the other hand also to availability. User anywhere will enter the wrong data. This is not because they are stupid, but because they are busy, and think of different ways with you. By typeof method to detect your function to accept input legality.

When in single quotes when double quotes

Although JavaScript them, double and single quotes can be expressed strings, to avoid confusion, we recommend the use of double quotes in HTML, use single quotes in JavaScript, but for compatibility with various browsers, and to parse can not go wrong when defining JSON objects, preferably double quotes.

deploy

1, with JSLint run JavaScript validator to make sure there are no syntax errors or code does not ask potential

2, it is recommended to use compression tool before deploying the JS file compression

3, unified file with UTF-8 encoding

4, JavaScript program should try to put .js file, when you need to call to include it in the <script src = "filename.js"> the form of HTML.

JavaScript code if it is specific to the HTML file, you should try to avoid writing JavaScript code directly in the HTML file. Because it would greatly increase the size of the HTML document, not conducive to the use of compression and caching code. Further, <script src = "filename.js"> tag should be placed later in the file, it is best placed before the </ body> tag.

This will reduce the load time due to load JavaScript code to affect the other components of the page.

Guess you like

Origin blog.51cto.com/14392904/2409725