JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
JavaScript Performance
Reduce Activity in Loops
Loops are used in programming.
Each statement in a loop, also the for statement, is executed for each iteration of the loop.
Statements or assignments that are placed outside the loop makes the loop run faster.
Bad:
for (let i = 0; i < arr.length; i++) {
Better Code:
let l = arr.length;
for (let i = 0; i < l; i++) {
Each time the loop is iterated, the bad code accesses the length property of an array.
The better code uses the length property outside the loop and makes the loop run faster.
Reduce DOM Access
Accessing the HTML DOM is very slow, compared to other JavaScript statements.
If you want to access a DOM element several times, access it once, and use it as a local variable.
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Performance</h2>
<p>If you expect to access a DOM element several times, access it once, and the use it as a local variable:</p>
<p id=”demo”></p>
<script>
const obj = document.getElementById(“demo”);
obj.innerHTML = ” Hello”;
</script>
</body>
</html>
Output
JavaScript Performance
If you expect to access a DOM element several times, access it once, and the use it as a local variable:
Reduce DOM Size
Keep The number of elements in the HTML DOM must be kept small.
This improves the page loading, and speed up rendering (page display), especially on smaller devices.
Every attempt to search the DOM (like getElementsByTagName) gives an advantage from a smaller DOM.
Avoid Unnecessary Variables
If you are not saving the value then don’t create new variables.
Replace code like this:
let fullName = firstName + ” ” + lastName;
document.getElementById(“demo”).innerHTML = fullName;
With this:
document.getElementById(“demo”).innerHTML = firstName + ” ” + lastName;
Delay JavaScript Loading
Inserting the scripts at the bottom of the page body allows the browser load the page first.
When a script is downloading, the browser does not start any other downloads. All parsing and rendering activity might be blocked.
The HTTP specification specifies that browsers must not download more than two components in parallel.
An alternative is to use defer=”true” in the script tag. The defer attribute defines that the script must be executed after the page has finished parsing, but it only works for external scripts.
If possible, add your script to the page by code, after the page has loaded:
Example
<script>
window.onload = function() {
const element = document.createElement(“script”);
element.src = “myScript.js”;
document.body.appendChild(element);
};
</script>
Avoid Using with
Avoid using the with keyword. It affects the speed. It also clutters up JavaScript scopes.
The with keyword cannot be used in strict mode.