What are some quick tips for increasing jQuery performance?
Paul Irish recently did a presentation on performance at the jQuery Conference 2009. The slides are some of the most comprehensive that I have seen.
Rather than doing:
$("#foo").addClass('test');
$("#foo").removeClass("bar");
$("#foo").slideUp('slow');
you can do:
$("#foo").addClass('test').removeClass('bar').slideUp('slow');
It's not really possible to increase the speed of jQuery, it really depends on how efficient your code is, how efficient the browser's JS interpreter is and how quick the computer running the code is. You could perhaps try and rewrite jQuery to make it more efficient, but that's going to take time and it's most likely already quite optimised.
One of the best ways to ensure efficiency is to make sure the *selector is targeting the element/class etc as specific as possible.
*$(SELECTOR)
- Prefer simple selection first only by ID, and second only by tag name. Selecting by class name or CSS selector requires jQuery to walk the DOM, while ID and tag map to "native" browser DOM functions (getElementById and getElementByTagName).
- Cache your jQuery objects as much as possible.
- Scope your operations to a root jQuery object. Rather than selecting elements individually, select a common ancestor element and use the
find
function to find elements within the scope of that elements children. This is really only optimal if you are performing some operations on the common ancestor anyway; otherwise the overhead of finding the ancestor and caching it may outweigh the benefit of scoped traversal. - Don't use
$.each()
, usefor(;;)
instead. It's over ten times faster.
it doeas apply always to common javascript: always cache, cache, cache e.g.:
var $this = $(this);
$this.css('width', parseInt($this.css('width')) + 20 + 'px');
Know when to use plain JavaScript instead of JQuery methods.
jQuery is an addition to JS+DOM, not a complete replacement for it. You don't have to use jQuery for every line of code you write. Some things are more succinctly expressed without it; many things are faster without it. Learn what the DOM makes available so you don't end up writing some of the sillier examples I've seen posted here.
eg.:
var ix= $('#'+selectname).children().index($('#'+selectname+' option:selected'));
faster, easier to read, doesn't break with unexpected characters in ID:
var ix= document.getElementById(selectname).selectedIndex;
I think you asking for code optimization, but since the performance highly depends on the used JavaScript-Engine, I'd like to mention Google Chrome Frame.