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
183 views
in Technique[技术] by (71.8m points)

javascript - jquery: fastest DOM insertion?

I got this bad feeling about how I insert larger amounts of HTML. Lets assume we got:

var html="<table>..<a-lot-of-other-tags />..</table>"

and I want to put this into

$("#mydiv")

previously I did something like

var html_obj = $(html); $("#mydiv").append(html_obj);

Is it correct that jQuery is parsing html to create DOM-Objects ? Well this is what I read somewhere (UPDATE: I meant that I have read, jQuery parses the html to create the whole DOM tree by hand - its nonsense right?!), so I changed my code:

$("#mydiv").attr("innerHTML", $("#mydiv").attr("innerHTML") + html);

Feels faster, is it ? And is it correct that this is equivalent to:

document.getElementById("mydiv").innerHTML += html ? or is jquery doing some additional expensive stuff in the background ?

Would love to learn alternatives as well.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try the following:

$("#mydiv").append(html);

The other answers, including the accepted answer, are slower by 2-10x: jsperf.

The accepted answer does not work in IE 6, 7, and 8 because you can't set innerHTML of a <table> element, due to a bug in IE: jsbin.


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

...