JavaScript Performance

How to speed up your JavaScript code.

Reduce activity within loops

Programming often uses loops.

Each iteration of the loop, every statement in the loop, including for will be executed.

Statements or assignments that can be placed outside the loop will make the loop run faster.

Poor code:

var i;
for (i = 0; i < arr.length; i++) {

Better code:

var i;
var l = arr.length;
for (i = 0; i < l; i++) {

Bad code will access the array's length .

Good code accesses properties outside the loop length properties, making the loop faster.

Reduce DOM access

Accessing the HTML DOM is very slow compared to other JavaScript.

If you expect to access a DOM element several times, access it only once and use it as a local variable:

Example

var obj;
obj = document.getElementById("demo");
obj.innerHTML = "Hello"; 

Try it yourself

Reduce the size of the DOM

Try to keep the number of elements in the HTML DOM to a minimum.

This will always improve page loading and speed up rendering (page display), especially on smaller devices.

Every time you try to search the DOM (for example getElementsByTagNameAll of them will benefit from a smaller DOM.

Avoid unnecessary variables

Do not create new variables that you do not intend to store values.

You can usually replace the code with:

var fullName = firstName + " " + lastName;
document.getElementById("demo").innerHTML = fullName; 

Use this code:

document.getElementById("demo").innerHTML = firstName + " " + lastName

Delay JavaScript loading

Please place the script at the bottom of the page to make the browser load the page first.

When the script is downloading, the browser will not start any other downloads. In addition, all parsing and rendering activities may be blocked.

The HTTP specification defines that the browser should not download more than two types of elements in parallel.

One option is to use defer="true"The 'defer' attribute specifies that the script should be executed after the page is fully parsed, but it only applies to external scripts.

If possible, you can add scripts to the page through code after the page is fully loaded:

Example

<script>
window.onload = downScripts;
function downScripts() {
    var element = document.createElement("script");
    element.src = "myScript.js";
    document.body.appendChild(element);
}
</script>

Avoid using with

Avoid using with keyword. It has a negative impact on speed. It also confuses the JavaScript scope.

in strict modeNot allowed The 'with' keyword.