Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...