Tales from the Office on Employee Recognition, Employee Rewards, Life Hacks, Gamification, and Human Resources.

Category Archives: Javascript

I have long heard that innerHTML is faster than creating elements, when you don’t need to store the DOM element in Javascript for further use. I had to do one such manipulation on Recognize’s pricing page.

Recognize’s pricing page copies text from the right features column for mobile considerations.

On page load our pricing page grabs the text of the features on the right column, and inserts the same text into the corresponding row. You can’t see it unless you resize your browser down to the size of a phone. We show the hidden copied text for mobile devices, because we can’t fit that right features column on 480px width devices, like the iPhone.

Recognize pricing page on an iPhone 4

I want this to happen fast. Because I loop over the DOM, the data is stored in the existing HTML. This is expensive, but allows me to keep my data DRY, and allow for devices that don’t have JS to at least view the site. Not to mention that it is important for the features to be in the HTML for SEO.

I profile my functions with console.time and console.timeEnd. For instance:

I’m doing a lot here. I’m looping over each feature’s list (Startup Package and Business Package), and for each line I create a new span and give it the same text as the corresponding feature’s list. It looks slow.

With string concatenation and innerHTML, it takes slightly longer at 49.706ms.

The results show that for this specific operation, it takes around 5 milliseconds longer with innerHTML. Somewhat counter intuitive on first impression due to the decreased lines of code. But knowing more about what is happening under the hood with +=, we find that += can be a slow.

Clearly, appending elements on each list item slows down the operation. It seems for my uses it is necessary, unless I was to strip out the entire DOM list item nodes and replaced them with a documentFragment. A strategy I believe to be overkill.

To avoid += string concatenation, many suggest using Array.join(). Modern browsers, like Chrome, don’t show any difference in performance. But let’s test anyway using this strategy, plus using jQuery to append a string.