Improve JavaScript Performance
Well, some of people out there say that avoiding DOM manipulation is a key to speed up javascript performance. Their understanding is pretty skewed. Actually, manipulating elements is really fast until it’s added to the DOM. There’s no need to set aside the wonderful prepend or append jQuery API’s and do some html tricks to get a promising performance. Just make sure that you’re manipulating element fragments just before they’re added to the DOM.
These two blocks of code has subtle difference which is very important.
//adds element to DOM and *then* does the manipulation
$('<div />').appendTo(someElement).doSomeManipulation();
//manipulates the element fragment *before* adding to the DOM
$('<div />').doSomeManipulation().appendTo(someElement);
It’s very important to know when elements have been added to the DOM, but be aware of manipulating them once they are being placed.
You could make awesome tweaks to your javascript performance by performing almost all of your work before adding your elements to the DOM. Simply reorder chain invocation and see incredible improvements to your javascript performance with this single technique.
At the end, this is not a necessary global fix for all javascript issues on performance. There may be some time that you actually need the element inserted into the DOM before manipulating it with jQuery, but it’s worth a try to see if this will work with your applications.