High-performance JavaScript

Source: Internet
Author: User

JAVASCIPRT Performance Optimization

This article is mainly after I read "High-performance JavaScript", want to record some useful optimization solutions, and in my own experience, to share with you,

The loading and execution of JavaScript
As we all know, the browser when parsing the DOM tree, when parsing to the script tag, will block all other tasks, until the JS file download, parsing execution is completed, will continue to execute down. Therefore, this time the browser will be blocked here, if the script tag in the head, then before the JS file load execution, the user can only see the blank page, so the user experience is certainly very bad. For this, the commonly used methods are the following:

Put all the script tags at the bottom of the body, so that the JS file is the last load and execution, you can first display the page to the user. However, you must first understand that the first screen rendering of the page depends on your part of the JS file, if so, you need to put this part of the JS file on the head.
Use defer, such as the following notation. When using defer this way of writing, although the browser resolves to the label, it will also download the corresponding JS file, but it will not be executed immediately, but will wait until the DOM parsing (before Domcontentloader) will execute these JS files. Therefore, the browser is not blocked.

The dynamic loading JS file, in this way, can be loaded after the page load, and then to load the required code, can also be implemented in this way JS file lazy load/On-demand loading, for example, now more common, is webpack combined vue-router/ The react-router implements on-demand loading, and the corresponding code is loaded only when the specific route is accessed. The specific method is as follows:
1. Dynamically insert script tags to load scripts, such as the following code

function Loadscript (URL, callback) {
Const SCRIPT = document.createelement (' script ');
Script.type = ' Text/javascript ';
Dealing with IE
if (script.readystate) {
Script.onreadystatechange = function () {
if (script.readystate = = = ' Loaded ' | | script.readystate = = = ' complete ') {
Script.onreadystatechange = null;
Callback ();
}
}
} else {
Handling of other browsers
Script.onload = function () {
Callback ();
}
}
script.src = URL;
Document.body.append (script);
}

Dynamic Loading JS
Loadscript (' File.js ', function () {
Console.log (' load complete ');
})
2. Load JS file by XHR mode, but in this way, you may face cross-domain problems. Examples are as follows:

Const XHR = new XMLHttpRequest ();
Xhr.open (' Get ', ' file.js ');
Xhr.onreadystatechange = function () {
if (xhr.readystate = = = 4) {
if (xhr.status >= && Xhr.status < | | xhr.status = = 304>) {
Const SCRIPT = document.createelement (' script ');
Script.type = ' Text/javascript ';
Script.text = Xhr.responsetext;
Document.body.append (script);
}
}
}
3. Merge multiple JS files into the same one and compress them. Cause: Most browsers already support parallel download JS file, but concurrent download there is a certain number of restrictions (browser-based, some browsers can only download 4), and, each JS file needs to establish an additional HTTP connection, Loading 4 25KB Files is much more time consuming than loading a 100KB file. Therefore, it is best to merge multiple JS files into the same one and code compression.

JavaScript scopes
When a function executes, an execution context is generated that defines the environment at which the function executes. When the function finishes executing, the execution context is destroyed. Therefore, calling the same function multiple times causes multiple execution contexts to be created. Every execution context has its own scope chain. I believe you should have known about the scope of this thing, for a function, its first scope is the variable inside its function. During the execution of a function, each occurrence of a variable is searched for the function's scope chain to find the first matching variable, first to find the variables inside the function, and then to look through the scope chain. Therefore, if we want to access the outermost variable (global variable), it will result in a relatively large performance loss compared to the variable directly accessing the internal. Therefore, we can store the frequently used global variable references in a local variable.

Const A = 5;
function Outter () {
Const A = 2;
function inner () {
Const B = 2;
Console.log (b); 2
Console.log (a); 2
}
Inner ();
}
The read of the object
In JavaScript, there are four types of literals, local variables, array elements, and objects. Access to literals and local variables is fastest, while access to array elements and object members is relatively slow. When accessing an object member, as with the scope chain, it is found on the prototype chain (prototype). Therefore, if the lookup member is too deep in the prototype chain, the access speed is slower. Therefore, we should reduce the number of lookups and nesting depths of the object members as much as possible. such as the following code

Perform two-time object member lookups
function Haseitherclass (element, className1, className2) {
return Element.classname = = = ClassName1 | | Element.classname = = = ClassName2;
}
optimization, if the variable does not change, you can use the local variable to save the contents of the lookup
function Haseitherclass (element, className1, className2) {
Const CURRENTCLASSNAME = element.classname;
return Currentclassname = = = ClassName1 | | Currentclassname = = = ClassName2;
}
Dom Operation optimization
Minimize the number of DOM operations, use JavaScript as much as possible, and store DOM nodes as much as possible with local variables. For example, the following code:
Before optimization, in each loop, you need to get the node with ID T, and set its innerHTML
function Innerhtmlloop () {
for (let count = 0; count < 15000; count++) {
document.getElementById (' t '). InnerHTML + = ' a ';
}
}
After optimization,
function Innerhtmlloop () {
Const TNODE = Document.getelemenbyid (' t ');
Const inserthtml = ";
for (let count = 0; count < 15000; count++) {
inserthtml + = ' a ';
}
tnode.innerhtml + = inserthtml;
}
As much as possible to reduce reflow and redraw, reflow and re-sink can be costly, so in order to reduce the number of reflow events, we can do the following optimizations
1. When we want to modify the DOM style, we should merge all the changes and process it as much as possible, reducing the number of reflow and re-sinks.

Before optimization
Const EL = document.getElementById (' test ');
El.style.borderLeft = ' 1px ';
El.style.borderRight = ' 2px ';
el.style.padding = ' 5px ';

Once optimized, the style is modified once, which reduces the three-time reflow to a single reflow
Const EL = document.getElementById (' test ');
El.style.cssText + = '; border-left:1px; border-right:2px; padding:5px; '
2. When we want to bulk modify the DOM node, we can hide the DOM node, and then make a series of modifications, and then set it to be visible, so that it can be up to two times reflow. The specific method is as follows:

Before optimization
Const ELE = document.getElementById (' test ');
A series of DOM modification operations

Optimization scenario One, the node to be modified is set to not display, then modify it, after the modification is complete and then display the node, so that only two times to rearrange
Const ELE = document.getElementById (' test ');
Ele.style.display = ' None ';
A series of DOM modification operations
Ele.style.display = ' block ';

Optimization Scenario Two, first create a document fragment (DocumentFragment), then modify the fragment, then insert the document fragment into the document, only the last time the document fragment inserted into the document will cause a reflow, so only one reflow is triggered ...
Const fragment = Document.createdocumentfragment ();
Const ELE = document.getElementById (' test ');
A series of DOM modification operations
Ele.appendchild (fragment);
3. Use Event Delegation: Event delegation is to move the event of the target node to the parent node to handle, because of the browser bubbling characteristic, when the target node triggers the event, the parent node also triggers the event. Therefore, the parent node is responsible for listening to and handling the event. So, what are the advantages of it? Suppose you have a list in which each list item needs to be bound to the same event, and this list can be frequently inserted and deleted. If you follow the usual method, you can only bind an event handler to each list item, and you will need to register the new event handler for the new list item whenever a new list item is inserted. In this case, if the list item is large, it will result in a particularly high number of event handlers, causing great performance problems. With event delegation, we only need to listen to the event on the parent node of the list item, and it can be handled uniformly. In this way, additional processing is not required for new list items. And the usage of the event delegate is actually very simple:

function Handleclick (target) {
Click Handling events for list items
}
function Delegate (e) {
Determines whether the target object is a list item
if (e.target.nodename = = = ' LI ') {
Handleclick (E.target);
}
}
Const PARENT = document.getElementById (' parent ');
Parent.addeventlistener (' click ', delegate);

High-performance JavaScript

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.