6 Ways I Keep My jQuery Optimized
In the past 2 months I've obsessed about optimizing the jQuery in my application. Ultimately, jQuery optimization comes down to reducing the amount of nodes getting filtered for a given query. Below are the top 6 ways I've managed make the speed of my jQuery independent of the size of the DOM.
-
Reduce the depth of selectors
Less code is faster! A smaller selector is less for jQuery to parse and less for jQuery to compare. Keep your selectors short and sweet: Instead of $(".menu .menu-item a") do $(".menu a").
-
Scope selectors by container.
always Always ALWAYS scope selectors. In jQuery this is done 2 ways:
1: $(container).find(selector)
2: $(selector, container) -
Give containers ID's
Scoping is important, but its pointless if the containers that are doing the scoping can't be found quickly. I gave every major container in my application a unique ID to efficiently scope selectors.
-
Don't Search More Than Necessary
Related to #1, the more jQuery searches, the slower it goes. When searching children use $(container).children(selector) NOT $(selector, container).
Likewise, when searching for a specific parent use $(container).closest(selector) rather than $(container).parents(selector). -
Use tag names in selectors
Do $("li.list-item") NOT $(".list-item").
Providing a tag name will allow jQuery to fetch all li elements using the much faster getElementsByTagName DOM API and search for ".list-item" rather than grabbing ALL elements and searching for ".list-item". -
Use Delegates!
Delegates are a very powerful tool. Delegates let you pick a container to listen for events of its children rather than finding all the specific children to listen to.
Example do $(container).delegate("a", "click", function(e) { ... }); NOT $("a", container).click(function(e) { .... });
- Posted Nov 10th, 2010 at 2:37 pm CST via web




Comments