I have a web app where we would be inserting hundreds of elements into the DOM
Essentially, I’m doing
$('#some_element').html('<lots of html here>');
repeatedly. In some cases I might need to do $('#some_element').appendTo('more html');
From previous experience inserting html text using the append or setting the innerHTML of an element is slow.
I’ve heard that you can increase performance by first putting the elements in a DOM fragment and then moving its location to inside the element you want.
The performance of this is key. Do you guys have any tips or suggestions on maximizing the performance? Any hacks I can do to make this fast?
Edit: as mentioned in a comment: The app involves a real-time stream of various data, so it needs to be able to constantly add new DOM elements to represent the new data. (This might also lead to another problem of having too many DOM elements, so would need to elements that are too old).
Just don’t do
html()(or use its native cousininnerHTML = …) repeatedly. Pack your HTML in one variable and dohtml()only once (or as few times as possible). E.g.:Also see the Quirksmode entry on innerHTML and the W3C DOM vs. innerHTML page.
Update: Yesterday I found the amazing article When innerHTML isn’t Fast Enough by Steven Levithan about his function
replaceHtml, which is even faster than using justinnerHTML, because it removes the DOM nodes that are to be replaced using standard DOM manipulation beforeinnerHTMLis used: