Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Tip – The Order Of JavaScript Operations Do Count

DZone's Guide to

Quick Tip – The Order Of JavaScript Operations Do Count

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}