In order to provide a fresh and unique user experience, many websites use JavaScript to improve design, verify forms, check browsers, as well as Ajax requests, cookie operations, etc., to achieve refresh-free dynamic effects. However, if you want to render a large amount of content in the browser, if it is not processed properly, the performance of the website will drop sharply. So it is necessary to understand how to improve the execution efficiency of JavaScript.
JavaScript functions
In JavaScript, functions are precompiled before use. Although sometimes strings can be used instead of functions, this JavaScript code will be re-parsed every time it executes, affecting performance.
1. Eval example
The code copy is as follows:
eval('output=(input * input)');
// It is recommended to change to:
eval(new function() { output=(input * input)});
2. SetTimeout example
The code copy is as follows:
setTimeout("alert(1)", 1000);
// It is recommended to change to:
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 you can take advantage of it.
The code copy is as follows:
var localVar = "global"; //Global variables
function test() {
var localVar = "local"; //Local variables
//Local variables
alert(localVar);
//Global variables
alert(this.localVar);
// Find the document and the local variable cannot be found, so look for the global variable
var pageName = document.getElementById("pageName");
}
Using local variables is much faster than using global variables, because the further away in the scope chain, the slower the parsing. The following figure shows the scope chain structure:
If there are with or try-catch statements in the code, the scope chain will be more complicated, as shown in the figure below:
JavaScript strings
A function in JavaScript that has a very performance impact is string concatenation. Generally, the + sign is used to implement the splicing of strings. However, early browsers did not optimize such connection methods, resulting in the continuous creation and destruction of strings that seriously reduced JavaScript execution efficiency.
The code copy is as follows:
var txt = "hello" + " " + "world";
It is recommended to change to:
The code copy is as follows:
var o = [];
o.push("hello");
o.push(" ");
o.push("world");
var txt = o.join();
Let's simply encapsulate:
The code copy 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 this:
The code copy is as follows:
var txt = new StringBuffer();
txt.append("Hello");
txt.append(" ");
txt.append("World");
alert(txt.toString());
JavaScript DOM Operation
HTML Document Object Model (DOM) defines a standard way to access and manipulate 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 and manipulate all nodes in an HTML document.
DOM repaint
Every time a DOM object modified to a page involves DOM redrawing, the browser will re-render the page. Therefore, reducing the number of modifications of DOM objects can effectively improve the performance of JavaScript.
The code copy is as follows:
for (var i = 0; i < 1000; i++ ) {
var elmt = document.createElement('p');
elmt.innerHTML = i;
document.body.appendChild(elmt);
}
It is recommended to change to:
The code copy is as follows:
var html = [];
for (var i = 0; i < 1000; i++) {
html.push('<p>' + i + '</p>');
}
document.body.innerHTML = html.join('');
DOM access
Each node in the HTML document can be accessed through the DOM. Every time you call getElementById(), getElementsByTagName() and other methods, the node will be re-finished and accessed. Therefore, cache the found DOM nodes can also improve the performance of JavaScript.
The code copy is as follows:
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
It is recommended to change to:
The code copy is as follows:
var elmt = document.getElementById("p2");
elmt.style.color = "blue";
elmt.style.fontFamily = "Arial";
elmt.style.fontSize = "larger";
DOM traversal
DOM traversal child elements usually read the next child element by index loop. In early browsers, this reading method is very efficient in execution. Using nextSibling method can improve the efficiency of traversal of DOM by js.
The code copy is as follows:
var html = [];
var x = document.getElementsByTagName("p");//All nodes
for (var i = 0; i < x.length; i++) {
//todo
}
It is recommended to change to:
The code copy is as follows:
var html = [];
var x = document.getElementById("div");//The superior node
var node = x.firstChild;
while(node != null){
//todo
node = node.nextSibling;
}
JavaScript memory release
In web applications, as the number of DOM objects increases, memory consumption will become larger and larger. Therefore, references to objects should be released in time so that the browser can recycle this memory.
Free the memory occupied by the DOM
The code copy is as follows:
document.getElementById("test").innerHTML = "";
Setting the innerHTML of the DOM element to an empty string can free the memory occupied by its child elements.
Release javascript object
The code copy is as follows:
//Object:
obj = null
//Object properties:
delete obj.property
//Array elements:
arr.splice(0,3);//Delete the first 3 elements