1) Use the Latest Version of jQuery
With all the innovation taking place in the jQuery project, one of the easiest ways to improve the performance of your web site is to simply use the latest version of jQuery. Every release of the library introduces optimizations and bug fixes, and most of the time upgrading involves only changing a script tag.
You can even include jQuery directly from Google’s servers, which provide
free CDN hosting for a number of JavaScript libraries.
The latter example will include the latest 1.6.x version automatically as it becomes available, but as pointed out on
css-tricks, it is cached only for an hour, so you better not use it in production environments.
2) Keep Selectors Simple
Up until recently, retrieving DOM elements with jQuery was a finely choreographed combination of parsing selector strings, JavaScript loops and inbuilt APIs like
getElementById()
,
getElementsByTagName()
and
getElementsByClassName()
. But now, all major browsers support
querySelectorAll()
, which understands CSS query selectors and brings a
significant performance gain.
However, you should still try to optimize the way you retrieve elements. Not to mention that a lot of users still use older browsers that force jQuery into traversing the DOM tree, which is slow.
1 | $( 'li[data-selected="true"] a' ) |
Selecting by id is the fastest. If you need to select by class name, prefix it with a tag –
$('li.selected')
. These optimizations mainly affect older browsers and mobile devices.
Accessing the DOM will always be the slowest part of every JavaScript application, so minimizing it is beneficial. One of the ways to do this, is to cache the results that jQuery gives you. The variable you choose will hold a jQuery object, which you can access later in your script.