JavaScript Performance

In the previous chapter we have seen common mistakes made by JavaScript Programmers.

In this chapter we will see how to improve speed of JavaScript(JavaScript Performance) code using some useful methods and tips.

Reduce calculation in Loop to Improve JavaScript Performance

Loops are parts of every programming language and use very frequently.

Every statement in a loop executes once for every iteration of a loop. It applies to all the assignments and calls inside for loop.

Bad Code

var studentNum;
for (studentNum = 0; studentNum < arrStudents.length; studentNum++) { 

Better Code

var studentNum;
var totStudent = arrStudents.length;
for (studentNum = 0; studentNum < totStudent; studentNum++) { 

In above example, bad code calculates total students every time loop iteration executes.

In better code, we have taken length property value in a variable outside loop. So length property is calculate only once irrespective of loop iterations.

Minimum use of Dom Access

JavaScript execution is very fast. However accessing Dom element using JavaScript is relatively slow.

If a Dom element is use several times, it is better to access it once and store it to local variable.

Example

var ele;
ele = document.getElementById("elementId");
ele.innerHTML = "This is set from JavaScript Dom Access"; 

Keep Dom Element as low as possible

Make sure to use Dom elements small in Number.

Low DOM elements in web page always improve Page speed because every DOM element takes its own time for rendering. Also search for any DOM element using JavaScript functions becomes slower.

Avoid Unnecessary Variables

Do not create new variable, unless it is require to use more than one place.

Example

var studentName = studentFname + " " + studentLname;
document.getElementById("studentName").innerHTML = studentName;

You can replace above code with:

document.getElementById("studentName").innerHTML = studentFname + " " + studentLname;

Load JavaScript at bottom

Make sure to load JavaScript files bottom of page because JavaScript loading delays page rendering. Putting it at the bottom of page lets browser loads page content first while loading JavaScript.

An alternative way is to use defer=”true” attribute in script tag. The defer attribute informs browser to load JavaScript files after page content loads. However it works only for external script.

You can add JavaScript files after page rendering using below code.

<script>
window.onload = loadScriptFile;

function loadScriptFile() {
    var element = document.createElement("script");
    element.src = "myFunction.js";
    document.body.appendChild(element);
}
</script>
<<< JavaScript Reserved WordsJSON Data, format, mime type and parsing >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .