Thursday, April 29th, 2010>p>Corey Hart has a fun post on jQuery micro optimization tips by walking through the jQuery codebase to see what is running.
Right away he notes that these are true micro optimizations, and to “use with caution and balance elegance with performance correctly.” Chances are you are a lucky chap if these are the biggest issues for performance on your application!
The post is still interesting as it shows a lot of jQuery core itself. I would think that Mr. “inline it” Dalton would approve of some of these tips :)
- jQuery.root: Internally, all selectors that don’t provide a context use jQuery( document ).find( selector ). Save yourself some ms, store the document root onto jQuery itself, and then run all global selectors off of that element.
- Context sucks, use find: Don’t get me wrong, you should always run selections based on a context if possible. But passing in a context to the jQuery constructor creates an extra unneeded function call. Internally jQuery runs context.find( selector ) anyway, so skip that step
- Live is terrible, delegate is awesome: The best part: delegate is live with a context. So why is live a bad idea? To use live, you first have to run a selection on the page, and then bind the live handler.
- jQuery.data > jQuery.fn.data: avoid jQuery(this)
- Bind and Trigger, get used to it: don’t use the short cut methods, save a function call
- Each is evil: there is only one true reason to use each, and that is when a closure is needed for each item. If you are just looping through an array, then the callback function gets triggered on every iteration. So using an array of 25 items, the callback gets triggered 25 times.
- Classes over styles: I would go so far as to say that using a class for a single style change is better than running through jQuery’s style module.
- Object.length, use it: Every jQuery selection comes with a length property that defines how many elements were found. Always check to make sure that there is a set of elements in your object before running a chain of methods.
Posted by Dion Almaer at 6:05 am