Performance of JavaScript code

There are ways to speed up your JavaScript code performance.

Reduction of activities in loops

Reduction of DOM Access

Example

<html>
   <body>
      <p id="dom"></p>
      <script>
         var obj;
         obj = document.getElementById("dom");
         obj.innerHTML = "Hello JavaScript..!!";
      </script>
   </body>
</html>

Output

Output

Reduction of DOM size

Avoid Unnecessary variables

Example

<html>
   <body>
      <p id="dom"></p>
      <script>
         var obj;
         obj = document.getElementById("dom");
         obj.innerHTML = "Hello JavaScript..!!";
      </script>
   </body>
</html>

Dom

After reduction or optimization

<p id="dom"></p>
<script>
   document.getElementById("dom").innerHTML = firstName + " " + lastName;
</script>

Delay JavaScript loading

When you put your JavaScript code at the bottom of the page, then the browser will load the page first.

While a script is downloading, the browser will not start any other downloads. In addition, all parsing and rendering might be blocked.

Note. The HTTP specification defines that the browsers should not download more than two components in parallel.

There is an alternative to use defer=” true” on your script page. This attribute specifies that the script should be executed before the page has finished the parsing, but it only works for external scripts.

You can also add your script by the code given below.

<script>
   window.onload = downScripts;

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

Avoid using the “with” keyword

Always avoid using the “with” keyword. It has a negative impact on speed and also clutters up the JavaScript scope. It is also not allowed in JavaScript “strict mode”.