Travis J
Travis J

Reputation: 82287

Is creating elements in javascript at runtime slower than classical HTML elements?

I am trying to figure out if creating elements to render to the DOM is slower than using simple HTML tags, such as <h2> for example.

I set out with this question and didn't find an answer here that I felt satisfied my curiosity. As a result, I decided to just make a simple test to run. This is not much of a question I realize as I am going to provide my findings but perhaps there are edge cases or others have some good tips.

I used some help from the mvc3 razor engine to generate large amounts of classic HTML elements.

Javascript Method:

<div id="appendHere">
</div>
<script type="text/javascript">
    var appenders = [];
    for(var i = 0; i < 10000; i++){
     var appenderIzer = document.createElement("h2");
     appenderIzer.innerHTML = "TestJs";
     document.getElementById("appendHere").appendChild(appenderIzer);
     appenders.push(appenderIzer);
    }
</script>

So here I am just going to be creating the element with javascript and then appending it to div element. I chose to store the elements in an array to see if that may also affect the loading performance.

Classical HTML (note the help of razor...writing out that many h2's could be tedious)

@for (int i = 0; i < 10000; i++)
{
 <h2>TestClassic</h2>
}

In the end there was really no difference, perhaps nanoseconds. There may be factors which would highlight this difference but in the other variations I could not find them.

Are these findings accurate? Is there a difference in the time it takes to render a page from pure HTML tags versus from javascript-created javascript-appended elements?

Upvotes: 3

Views: 1392

Answers (1)

Chase Seibert
Chase Seibert

Reputation: 15841

Inserting DOM elements into an already rendered page is much slower than rendering those same elements from a page refresh. How much slower depends on how you do the insertions. It's also largely dependent on how much styling you have, and how many layers of nested DOM there are. Browser version is also critical.

Here is some (out of date) information:

As you can see, the performance in IE7 degrades dramatically as the complexity of the HTML increases. If you put a timer before the innerHTML setter, you will see that the time increase to that point is negligible. It's actually not a javascript performance problem at all; it's DOM insertion performance!

Up to 70% of IE performance is spent in rendering and layout, according to Microsoft.

Upvotes: 1

Related Questions