Skip to main content

Improve JavaScript Performance

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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.

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn how Git works, and how to use it to streamline your workflow!


Google, Netflix and ILM are Python users. Maybe you should too?