JavaScript

How to Speed up the Execution of JavaScript Code

When developing an app or a website, one of the most crucial elements to consider is the app’s or website’s performance. As a user, I wouldn’t want any app to take a long time to load or whenever I click something and I have to wait for some action. Often if the webpage takes 5-6 seconds to load most users including me would leave the webpage.

For web developers, JavaScript is a fantastic tool. Every web developer learned JavaScript at some point in their life. However, poor JavaScript code results in slower websites.

With this in mind, a developer always looks at ways of improving his webpage. You are in luck because today we are going to talk about how to speed up the execution of JavaScript code.

Activities reduction in Loops

A programmer often uses loops to shorten his code. However, it should be kept in mind that there are some bad ways of using loops that make your program slow.

Let’s take a “for” loop example.

Example:

for(let i=0; i < myArray.length; i++){
   //Hello
}

This loop is programmatically right but its performance will be bad. We can put the myArray.length statement outside the loop so that it doesn’t have to calculate the length again and again until the loop ends.

Solution:

let len=myArray.length;
for(let i=0; i < len; i++){
   //Hello
}

In this loop, we can see that the length is fixed and the loop doesn’t have to calculate the length of an array every time it iterates. Hence, speed increases and so does the performance.

Dom Access Reduction

If we compare the JavaScript statement to accessing HTML Dom, we will find that accessing HTML Dom is very slow. This is not a problem if we are not accessing or performing many Dom operations. However, when you perform many dom operations it does affect the speed of the webpage.

The solution for this is to store the Dom element in a local variable and then we can access that multiple times.

For Example:

const myObj=document.getElementById("speed"),innerHTML="not achieved";
const myObj=document.getElementById("speed").hidden="false";
//slow and hinders speed

This makes our program execute inefficiently.

Let’s look at another example that tackles this problem.

const myObj=document.getElementById("speed");
myObj.innerHTML="achieved";
myObj.hidden="false";

Now that we have looked at Dom access reduction, let us shine the light on dom size reduction to improve the speed of our webpage in JavaScript.

Dom Size Reduction

Before going into the dom size reduction, let us look at excessive dom size which means that your page has too many dom nodes/HTML components if the dom size is too large. It can also mean that your page dom elements are deeply nested. This results in the consumption of more power, hence reducing page performance or speed.

The solution is that the number of elements should be minimized in the HTML Dom. The advantage of this is that it will improve the loading of the page as well as speeding the rendering process which is the displaying of the page. It is very handy especially on smaller devices like mobile phones etc.

Eliminating Unnecessary Variables

This is the simplest trick to enhance your webpage performance. Why make variables when they are not needed? Also, why make variables where you know you are just using it for displaying it somewhere? When we avoid making unnecessary variables our web page performance increases.

For Example bad code:

let firstName="Jhon";
let lastName="Cena";
let fullName=firstName+" "+lastName;
alert(fullName);

In this example, we can see that we are storing the firstName and the lastName in fullName just to display it in an alert. Wouldn’t it be better to directly alert the firstName and lastName? This is what eliminating unnecessary variables is.

Solution (good code):

let firstName="Jhon";
let lastName="Cena";
alert(firstName+" "+lastName);

Delay Loading of JavaScript

To enhance your webpage performance in JavaScript, it is a common practice to put a script tag or within the script tag the JavaScript code at the end of the HTML page. The main purpose is that the browser should load the HTML first and then the JavaScript code. To put it in technical terms, while a script is downloading, the browser will not initiate any other downloads and all parsing and rendering will be blocked.

We can also use “defer=”true”” in our script tag. The function of defer attribute is that it specifies that the script should only be executed once the page is finished parsing. In other words, it waits until the whole DOM is loaded. It should be noted, however, that it is only compatible with external scripts.

Example:

<script>
       window.onload = function() {
         const ele = document.createElement("script");
         ele.src = "code.js";
         document.body.appendChild(ele);
       };
</script>

Avoid using the keyword “with”

With keyword is used to reference the properties or methods of an object as it is a kind of shorthand. Using the keyword “with” slows down speed. The other reason not to use the with keyword is that it clutters up scopes of JavaScript.

Minify JavaScriptCode

Minifying or minimization of JavaScript code is another method of speeding up the execution of our JavaScript code. Minifying JavaScript code simply means removing or altering all the unwanted and unnecessary characters within JavaScript source code but without changing the functionality of the program. It includes multiple things like removing comments, semicolons as well as whitespaces. Apart from this it also involves the usage of short function and variable names. Let us see an example before and after minification of our code:

Before Minifying:

//the function
//which console log

//the first message from person

function firstMessage(name){
  console.log("First Message is from: ",name);
}
//now call the function

firstMessage("John");

After Minifying:

function fMsg(n){console.log("First Message is from: ",n)}firstMessage("John");

Conclusion

A developer always maintains the balance between the reliability and the optimization of the code. It is for this reason we discussed how to speed up the execution of JavaScript code in this article. All the tips and tricks mentioned above when used together will have a significant improvement on the speed of JavaScript code.  However one should keep in mind that although performance is necessary it is not above detecting errors or adding functionalities.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.