Ankit Gupta
Ankit Gupta

Reputation: 189

What are the performance cosiderations when creating HTML elements from JavaScript?

I want to create an HTML section using JavaScript, so I have two options:

  1. I can create HTML elements using createElement() function:

    document.createElement('div');
    
  2. I can directly create elements like "<div>Test</div>" as a string.

Which one is better in performance?

Upvotes: 3

Views: 1555

Answers (4)

dima.y
dima.y

Reputation: 31

From the benchmarks below it seems that innerHtml is considerably faster than using the DOM methods (I tried using Chrome and IE):

http://www.quirksmode.org/dom/innerhtml.html#t10

http://jsperf.com/realistic-innerhtml-vs-appendchild/15

Upvotes: -1

skeep
skeep

Reputation: 940

Everytime you call DOM manipulation method, browser have to calculate the relative position and size of all the elements on the page. and render it again. This process is called reflow. An old but still good article on reflow can be found here http://ajaxian.com/archives/browser-reflows-how-do-they-affect-performance .

Now that being said, updating DOM is a costly affair. And it should be used optimally used. What Benjamin mentioned is correct. But if you continue updating the DOM directly it will trigger reflow repeatedly, which might slow down the performance.

What can a be a better approach is to use DocumentFragment. A very quick explanation can also be found by David Walsh.

Upvotes: 2

Vitim.us
Vitim.us

Reputation: 22138

Is a bit off topic, but I think is a important point if anyone is going to use innerHTML

This is very wrong:

container.innerHTML = "<div>";
container.innerHTML += "Hello ";
container.innerHTML += "World";
container.innerHTML += "</div>";

If you really need to make up the string, only append it when the html is completed, you don't want to invoke the parser multiple times with incomplete html.

var html;
html = "<div>";
html += "Hello ";
html += "World";
html += "</div>";

container.innerHTML = html;

Another point is that innerHTML will parse everything again and will remove any event handlers attached to the elements inside a container.

container.innerHTML += moreContent; //previous content lost their event handlers

With DOM you don't need to worry about it, only the new content will be parsed.

container.appendChild(moreContent);

Upvotes: 2

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

Using the DOM API directly is much faster since it does not have to invoke the HTML parser.

 var div = document.createElement("div");
 container.appendChild(div);

Is considerably faster than

 container.innerHTML += "<div></div>";

However, in most cases unless you're doing performance sensitive things, use the one that creates more readable code.

Upvotes: 4

Related Questions