jQuery Micro Optimizations

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 🙂

  1. 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.
  2. 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
  3. 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.
  4. jQuery.data > jQuery.fn.data: avoid jQuery(this)
  5. Bind and Trigger, get used to it: don’t use the short cut methods, save a function call
  6. 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.
  7. 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.
  8. 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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s