Quick Tip – The Order Of JavaScript Operations Do Count

April 2, 2013

no comments

Quick Tip – The Order Of JavaScript Operations Do Count

Continuing the quick JavaScript performance tips (tip1 and tip2) I wrote, here is another thing to consider when writing your JavaScript code. The order of your operations can decrease your performance. Sometimes all you have to do is think about what you are doing and then you might avoid pitfalls like in the next scenario.

The Scenario

Lets look at an example of adding a new div element to the Document Object Model (DOM):  

function addDiv(parentElement, text) {
  var element = document.createElement('div');
  parentElement.appendChild(element);
  element.textContent = text;

}

The function will add a new div element to the parent element and then change its text. What’s the problem with that? We are doing a trivial thing. The problem is the order of the operations which can trigger two reflows, one for appending the child and the other for changing the text.

Suggested Solution

Lets change the previous code sample and avoid the problem:

function addDiv(parentElement, text) {
  var element = document.createElement('div');
  element.textContent = text;
  parentElement.appendChild(element);

}

Putting the appendChild function at the end solves the problem and might trigger only one reflow. All the changes to the div are being done in memory and not on a DOM element.

Summary

The order of operations do count when dealing with JavaScript and browsers. When you have a set of operations don’t write the code as is, test it and check that you are not falling into pitfalls like triggering reflows.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>