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.
innerHTML is remarkably fast, and in many cases you will get the best results just setting that (I would just use append).
However, if there is much already in ‘mydiv’ then you are forcing the browser to parse and render all of that content again (everything that was there before, plus all of your new content). You can avoid this by appending a document fragment onto ‘mydiv’ instead:
In this way, only your new content gets parsed (unavoidable) and the existing content does not.
EDIT: My bad… I’ve discovered that innerHTML isn’t well supported on document fragments. You can use the same technique with any node type. For your example, you could create the root table node and insert the innerHTML into that: