8

I have a big piece of code that needs to be inserted into DOM at some point. The code also contain some variables:

<ul id="info'+value+'" class="info"><li class="hide"></li><li class="lock"><ul>
// just a piece of the code with variable "value"

Right now I am doing:

var codeToInsert = "<some code/>"
codeToInsert.insertAfter('#someID');

Is there a better way to do it from the performance point of view?

Gopi
  • 10,073
  • 4
  • 31
  • 45
Mircea
  • 11,373
  • 26
  • 64
  • 95
  • can you expand a little example of html code. Is this code comes via ajax?, Can this be some delimiter to split the html code, come in parts per json? – andres descalzo Sep 08 '10 at 13:32

2 Answers2

9

If you want to insert big piece of code, use jQuery for its selector and then use the innerHTML DOM property - it is the fastest way to insert a big chunk of HTML. Do not wrap the string that is to be inserted into JQuery, leave it as a string.

E.g.: $('#somePlaceholder')[0].innerHTML = myHTMLString;.

http://www.quirksmode.org/dom/w3c_html.html:

In general innerHTML is faster than normal DOM methods because the HTML parser is always faster than the DOM engine. If you want to do complicated changes, use innerHTML. (For simple changes it does not really matter which method you use, although innerHTML remains theoretically faster.)

If you do string concatenation in JS, create an array, push() the parts and join() at the end instead of appending with e.g. += or +. It makes a difference esp. in IE.

Andras Vass
  • 11,478
  • 1
  • 37
  • 49
0

Top of my head, you can also use .append(), .appendT(), .before(), .after() etc. Check this for a range of such functions: http://api.jquery.com/category/manipulation/

Sidharth Panwar
  • 4,606
  • 6
  • 27
  • 36
  • I doubt that would make any difference, performance wise. It's only a slightly different syntax to do what is essentially the same thing. – Yi Jiang Sep 08 '10 at 12:05
  • The only place where you may save on performance is selection of the place where you want to insert the code, I think. Don't think they differ from each other in terms of performance that much. But still have a look and try to see if you find one better than the other. – Sidharth Panwar Sep 08 '10 at 12:07
  • insertAfter() gives me the possibility to position this right where I want, as where append() will place this to a div that needs to be created or already exists. Can be dome also with append but rather them semantics may be the same thing as performance... – Mircea Sep 08 '10 at 12:07
  • I think .insertxxx would work better if you're iterating through child elements whereas .appendxxx would be good if you want to move to a particular object (whose relationship with its siblings is not relevant). Slightly twisted but that's the best reason for using one and not the other I think. – Sidharth Panwar Sep 08 '10 at 12:16