11. Cache is awesome Use it as often and as much as you can Limited DOM traversal = Better performance var $h2s = $('#container h2'); $h2s.css('border', '1px solid #666666'); $h2s.click( function() { $(this).next('div').slideToggle(); });
12. 'Context' is fast. 'Find' is faster. Try not to involve the Sizzle engine if you can $('child', $('#parent')); (internally calls) $('#parent').find('child');
14. Bind() Vs Live() Vs Delegate() Understand what each does. Use appropriately. $('#sometable').each(function(){ $('td', this).bind('hover', function(){ $(this).toggleClass('hover'); }); }); $('#sometable').each(function(){ $('td', this).live('hover', function(){ $(this).toggleClass('hover'); }); }); $('#sometable').delegate('td', 'hover', function(){ $(this).toggleClass('hover'); });
15. Native calls Vs jQuery Native calls are always faster even if a tad bit For example, $(this).attr('id'); // Fast this.id; // Faster
16. Limit DOM manipulation Create what you need in memory. Then update the DOM. BAD var $mylist = $('#mylist'); // <ul> for (vari = 0; i < 100; i++) { $mylist.append('<li>' + bestsellers[i] + '</li>'); } GOOD var $mylist = $('#mylist'); // <ul> varconcatenatedList = “”; for (vari = 0; i < 100; i++) { concatenatedList += ('<li>' + bestsellers[i] + '</li>'); } $mylist.append(concatenatedList);
17. Event delegation Bind fewer events to the elements for better performance. BAD $('#myListli).bind('click', function() { // do stuff }); GOOD $('#myList).bind('click', function(e){ var target = e.target; if (target.nodeName === 'LI') { // do stuff } });
Position selectors :first, :last, :even, :odd, :gt, :lt, :eqEasy Form selectors :input, :text, :checkbox, :file, :password, :submit, :image, :reset, :buttonFor example, querySelectorAll doesn’t work in IE7 or lower. Sizzle kicks in then.
Users will often start using the page before it finishes loading. Google Analytics and other scripts can cause the DOMContentLoaded event fire long after the page appears to be loaded.
var $myBox = $('#test'); alert($myBox.html()); //This works.