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.
jQuery is a wrapper that normalizes DOM manipulation in a way that works consistently in every major browser. It's fully reasonable for it to perform 25x slower than direct DOM manipulation. The performance loss is a tradeoff to have concise code.
getElementById is the fastest.
Most time takes the DOM-insertion of newly created Elements, and therefor insertion of every single new element is slow. A faster way is to create a documentFragment , append all new elements to that in the structure you need and then add the complete fragment to the DOM.
Answer. When there is a change to an element in the DOM, the DOM has to re-render the element and all of the element's children to the DOM - making DOM manipulation very slow in comparison to the Virtual DOM.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With