While writing JavaScript can be fraught with peril as it is very easy to introduce slow running code, keeping some simple guidelines in mind could keep your enterprise application from running too slow.
First of all, traversing the DOM can be expensive. You want to minimize the number of times you invoke document.getElementById
and, even worse, document.getElementsByTagName
. Capturing a reference to a DOM element into a variable and using the variable can save on expensive calls to the DOM.
So instead of implementing the following code:
document.getElementsById("elementId").setAttribute("data-position", 1); document.getElementsById("elementId").setAttribute("data-position", 1);
Or implementing its equivalent in jQuery:
$("#elementId").attr("data-position", 1); $("#elementId").attr("data-position", 1);
You can implement the following code:
var element= document.getElementsById("elementId"); element.setAttribute("data-position", 1); element.setAttribute("data...