Javascript jQuery best way to insert a big piece of code into DOM

后端 未结 2 1902
死守一世寂寞
死守一世寂寞 2020-12-16 22:54

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

相关标签:
2条回答
  • 2020-12-16 23:32

    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/

    0 讨论(0)
  • 2020-12-16 23:36

    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.

    0 讨论(0)
提交回复
热议问题