Welcome Guest. Sign in or Signup

1 Comments

How to improve the performance of your java script in your page?

Asked by: 5618 views
d) Performance

+1
0

Performing as many changes as possible outside of the live DOM structure will improve the performance.

Here are some highlights from the following pages:
http://www.nczonline.net/blog/2009/02/03/speed-up-your-javascript-part-4/
http://gent.ilcore.com/2011/03/how-not-to-trigger-layout-in-webkit.html
http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
http://www.youtube.com/watch?v=mHtdZgou0qU

Note that the follow things will affect the performance:

a) When you add or remove a DOM node

Let us say you have code like below to add items to the DOM:

for (var i=0; i < items.length; i++){
    var item = document.createElement("li");
    item.appendChild(document.createTextNode("Option " + i);
    list.appendChild(item);
}

The above code is inefficient because it touches the live DOM each time through the loop. To increase performance, you should minimize this number. The best option, in this case, is to create a document fragment as an intermediate placeholder for the created li elements and then use that to add all of the elements to their parent:

var fragment = document.createDocumentFragment();
for (var i=0; i < items.length; i++){
    var item = document.createElement("li");
    item.appendChild(document.createTextNode("Option " + i);
    fragment.appendChild(item);
}
list.appendChild(fragment);

b) When you apply a style dynamically

element.style.backgroundColor = "blue";
element.style.color = "red";
element.style.fontSize = "12em";

This code has three style changes…and also three reflows. A reflow happens with every change in style to this element. If you’re going to be making a number of changes to an element’s style, it’s best to group those in a CSS class and then change the class using JavaScript rather than applying individual style changes manually. For example:

.newStyle {
    background-color: blue;
    color: red;
    font-size: 12em;
}

Then the JavaScript becomes a single line:

element.className = "newStyle";

1 Comments



  1. this source on Dec 18, 2014 Reply

    I am so grateful for your article.Really thank you! Awesome.


Comments on Question