2

In my web application, The initial divs required are downloaded first. Then, I send a request and get the additional absolute divs(pop up divs/warning msg divs etc.,) using ajax call. Now what I do is the below

document.body.innerHTML += secondarydivs;

Will this cause a performance hit as the body is already constructed and now I am appending even more divs? What I exactly need to know is, when this statement is excecuted, is the whole document repainted or only the additonal string gets parsed added to the DOM?

Thanks!

Gautham Renganathan
  • 647
  • 1
  • 9
  • 18
  • 1
    [**See similar question**](http://stackoverflow.com/questions/2319472/should-you-add-html-to-the-dom-using-innerhtml-or-by-creating-new-elements-one-b) – Anirudh Ramanathan Nov 15 '12 at 10:12
  • That's fine. Just consider that the secondarydivs you're adding as strings won't be available in DOM until you release the thread (eg. your JS call stack quits). So if you have to reference them just after the innerHTML addition, do it with a setTimeout(fn,0), or create them with document.createElement. – LittleSweetSeas Nov 15 '12 at 10:15
  • @LittleSweetSeas actually I am not so sure anymore if I was wright, according to Cthulhu's link I was wrong. Just for reference: I wrote that innerHTML according to my knowledge is faster than for example document.createElement and I do not know anything faster than it – mkk Nov 15 '12 at 10:16

2 Answers2

3

It will serialize the DOM to HTML, destroy all the existing nodes (losing bound event handlers in the process), then recreate them (and the new nodes) from the HTML.

Use appendChild and friends.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

It depends what exactly you do with it. if it's just a single statement in some kind of callback function, than it's ok, but if you set it in a loop, you should consider constructing the whole thing as a string and than appending it to the innerHTML.

Headshota
  • 21,021
  • 11
  • 61
  • 82