I have used jQuery quite a lot recently and have picked up some good practice’s and dropped some bad habits, so I thought I’d share what I have learnt, it’s not ground-breaking but simply performance enhancing tips.
Loading jQuery
Using Google Code to load jQuery gives you a several advantages over saving it locally to your server. The most important factor is that the library is probably already cached on the clients machine. If not this is not the case, it’s fast to download from Google’s CDN and saves on your own bandwidth:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Selection
To begin with I used this syntax to select elements on the DOM:
Then I discovered that the find method is up to 70% faster. So use this method where possible:
$('#parent').find('.child');
Chaining
jQuery allows you to chain your functions, which helps you cut down on your selector use too:
$('#parent').find('.child').removeClass('off').addClass('on');
Caching
Try and keep your selectors to a minimum by storing regularly accessed elements in variables. You should just select it once and keep the selection in memory by storing it in a variable for access:
var cachedElement = $('#element');
for(i = 0; i < 1000; i++){
cachedElement.append('Index: ' + i);
}
Cheat Sheet
I recommend having a cheat sheet close at hand whatever language you are using:
Download jQuery 1.7 Visual Cheat Sheet
Hope this helps you improve you jQuery.