Increase the Speed of JavaScript Code

Increase the Speed of JavaScript Code

·

3 min read

JavaScript is an integral part of every webpage, mobile app and web-based software. While JavaScript's client side scripting capabilities can make applications more dynamic and engaging, it also introduces the possibility of inefficiencies by relying on the user's own browser and device. Consequently, poorly written JavaScript can make it difficult to ensure a consistent experience for all users.

So here are some following tips that will help you:

1. Reduce Activity in Loops:

We all know, loops are commonly used in programming and each statement in a loop, including the for statement and is executed for each iteration of the loop.

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

Bad code:

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

Here bad code have to access the length property of array each time until the loop is iterated.

Good code:

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

Here good code only access the length property only one time and makes the loop run faster.

2. Reduce DOM Access

While comparing to JavaScript statements, Accessing the HTML DOM is very slow. Thus, if you want to expect DOM element several times then just access it once and use it as a local variable.

Bad code:

document.getElementById("demo").innerHTML = "Hello";
document.getElementById("demo").innerHTML = "How are you..!";

Here in Bad code, we are accessing DOM element each time when required.

Good code:

var obj;
obj = document.getElementById("demo");
obj.innerHTML = "Hello";
obj.innerHTML = "How are you..!";

Here in Good code, we are accessing DOM element one time and use it as a local variable.

3. Avoid Unnecessary Variables

Don't create new variables if you don't plan need it in future.

Bad code:

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

Here I don't need fullName variable for further computation so I can replace this code with following code easily.

Good code:

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

4. Delay JavaScript Loading

Putting your scripts at the bottom of the page body allows your browser to load the page fast as script is downloading, the browser will not start any further downloads.

In Addition, you can add the following script to the page by code after the page loads.

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

So these are the some tips that I want to discuss with you. Please share your own tips that you think can help other.

IF YOU LIKE THIS ARTICLE, DO REACT AND FOLLOW ME FOR MORE INFORMATIVE STUFF LIKE THIS.❤