SlideShare a Scribd company logo
jQuery Performance Rules I hear...I forget I see...and I remember I do...and I understand - Ancient Chinese Proverb
No best practices Browser has to do more work Impacts performance – CPU utilization
1. Always Descend From an #id <div id=&quot;content&quot;> <form method=&quot;post&quot; action=&quot;/&quot;> <h2>Traffic Light</h2> <ul id=&quot;traffic_light&quot;> <li><input type=&quot;radio&quot; class=&quot;on&quot; name=&quot;light&quot; value=&quot;red&quot; /> Red</li> <li><input type=&quot;radio&quot; class=&quot;off&quot; name=&quot;light&quot; value=&quot;yellow&quot; /> Yellow</li> <li><input type=&quot;radio&quot; class=&quot;off&quot; name=&quot;light&quot; value=&quot;green&quot; /> Green</li> </ul> <input class=&quot;button&quot; id=&quot;traffic_button&quot; type=&quot;submit&quot; value=&quot;Go&quot; /> </form> </div>  Selecting the button like this is slower:  var traffic_button = $('#content .button');   Instead, select the button directly:  var traffic_button = $('#traffic_button');   When selecting multiple elements, always descend from the closest parent ID. var traffic_lights = $('#traffic_light input');
2. Use Tags Before Classes <div id=&quot;content&quot;> <form method=&quot;post&quot; action=&quot;/&quot;> <h2>Traffic Light</h2> <ul id=&quot;traffic_light&quot;> <li><input type=&quot;radio&quot; class=&quot;on&quot; name=&quot;light&quot; value=&quot;red&quot; /> Red</li> <li><input type=&quot;radio&quot; class=&quot;off&quot; name=&quot;light&quot; value=&quot;yellow&quot; /> Yellow</li> <li><input type=&quot;radio&quot; class=&quot;off&quot; name=&quot;light&quot; value=&quot;green&quot; /> Green</li> </ul> <input class=&quot;button&quot; id=&quot;traffic_button&quot; type=&quot;submit&quot; value=&quot;Go&quot; /> </form> </div>  Always prefix a class with a tag name (and remember to descend from an ID):  var active_light = $('#traffic_light input.on');
3. Cache jQuery Objects Cache jQuery objects to a variable, never repeat a jQuery selection in your application. For example, never do this… $('#traffic_light input.on).bind('click', function(){...}); $('#traffic_light input.on).css('border', '3px dashed yellow'); $('#traffic_light input.on).css('background-color', 'orange'); $('#traffic_light input.on).fadeIn('slow'); Instead, first save the object to a local variable, and continue your operations: var $active_light = $('#traffic_light input.on'); $active_light.bind('click', function(){...}); $active_light.css('border', '3px dashed yellow'); $active_light.css('background-color', 'orange'); $active_light.fadeIn('slow');  Storing jQuery results for later $my = {  head : $('head'),  traffic_light : $('#traffic_light'),  traffic_button : $('#traffic_button')    };
4. Harness the Power of Chaining This allows us to write less code, making our JavaScript more lightweight.   var $active_light = $('#traffic_light input.on'); $active_light.bind('click', function(){...})  .css('border', '3px dashed yellow') .css('background-color', 'orange') .fadeIn('slow');
5. Use Sub-queries jQuery allows us to run additional selector operations on a wrapped set. This reduces performance overhead on subsequent selections since we already grabbed and stored the parent object in a local variable. var $traffic_light = $('#traffic_light'), $active_light = $traffic_light.find('input.on'), $inactive_lights = $traffic_light.find('input.off');  Tip: You can declare multiple local variables by separating them with commas – save those bytes!
6. Limit Direct DOM Manipulation The basic idea here is to create exactly what you need in memory, and then update the DOM. This is not a jQuery best practice, but a must for efficient JavaScript. For example, if you need to dynamically create a list of elements, do not do this:  var top_100_list = [...], // assume this has 100 unique strings $mylist = $('#mylist'); // jQuery selects our <ul> element for (var i=0, l=top_100_list.length; i<l; i++)  {   $mylist.append('<li>' + top_100_list[i] + '</li>');  }  Instead, we want to create the entire set of elements in a string before inserting into the DOM:   var top_100_list = [...], // assume this has 100 unique strings  $mylist = $('#mylist'), // jQuery selects our <ul> element  top_100_li = &quot;&quot;; // This will store our list items  for (var i=0, l=top_100_list.length; i<l; i++) {   top_100_li += '<li>' + top_100_list[i] + '</li>';  }   $mylist.html(top_100_li);
7. Leverage Event Delegation (a.k.a. Bubbling) Every event (e.g. click, mouseover, etc.) in JavaScript “bubbles” up the DOM tree to parent elements. This is incredibly useful when we want many elements (nodes) to call the same function. A binding like this is inefficient. $('#entryform input).bind('focus', function(){  $(this).addClass('selected');  }).bind('blur', function(){  $(this).removeClass('selected');  });  Instead, we should listen for the focus and blur events at the parent level. $('#entryform).bind('focus', function(e){  var cell = $(e.target); // e.target grabs the node that triggered the event.  cell.addClass('selected');  }).bind('blur', function(e){  var cell = $(e.target); cell.removeClass('selected'); });  The parent node acts as a dispatcher and can then do work based on what target element triggered the event.
8. Eliminate Query Waste Although jQuery fails nicely if it does not find any matching elements, it still takes time to look for them. If you have one global JavaScript for your entire site, it may be tempting to throw every one of your jQuery functions into   $(document).ready(function(){ // all my glorious code })  Your Global JS library would look something like this:   var mylib = {  article_page :  {  init : function()  {  // Article page specific jQuery functions.  }  },  traffic_light :  {  init : function()  {  // Traffic light specific jQuery functions.  }  }   }
9. Defer to $(window).load Although  $(document).ready  is incredibly useful, it occurs during page render while objects are still downloading. If you notice your page stalling while loading, all those  $(document).ready  functions could be the reason why.  You can reduce CPU utilization during the page load by binding your jQuery functions to the  $(window).load  event, which occurs after all objects called by the HTML (including <iframe> content) have downloaded. $(window).load(function(){ // jQuery functions to initialize after the page has loaded. }); Superfluous functionality such as drag and drop, binding visual effects and animations, pre-fetching hidden images, etc., are all good candidates for this technique.
Recap Always Descend From an #id  Use Tags Before Classes  Cache jQuery Objects  Harness the Power of Chaining  Use Sub-queries  Limit Direct DOM Manipulation  Leverage Event Delegation (a.k.a. Bubbling)  Eliminate Query Waste  Defer to $(window).load
 

More Related Content

PPT
WordPress Third Party Authentication
ODP
Mojolicious on Steroids
PPT
Introduction to JQuery
PPTX
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
PDF
Mojolicious, real-time web framework
ODP
Drupal Best Practices
PDF
Mojolicious: what works and what doesn't
PDF
How Kris Writes Symfony Apps
WordPress Third Party Authentication
Mojolicious on Steroids
Introduction to JQuery
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious, real-time web framework
Drupal Best Practices
Mojolicious: what works and what doesn't
How Kris Writes Symfony Apps

What's hot (20)

KEY
jQuery Plugin Creation
PDF
Plugin jQuery, Design Patterns
KEY
Mojolicious - A new hope
PPTX
J Query - Your First Steps
PPT
PDF
Matters of State
PDF
Keeping it Small: Getting to know the Slim Micro Framework
PDF
Keeping it small - Getting to know the Slim PHP micro framework
KEY
jQuery Anti-Patterns for Performance & Compression
PPTX
Childthemes ottawa-word camp-1919
PPT
Smarter Interfaces with jQuery (and Drupal)
PPT
Jquery Best Practices
PPTX
jQuery Best Practice
PDF
How Kris Writes Symfony Apps
PPT
JQuery: Introduction
PPTX
Automating boring tasks with Powershell
PPTX
Maintainable JavaScript 2012
PDF
Task 1
PDF
Extending the WordPress REST API - Josh Pollock
PDF
Love and Loss: A Symfony Security Play
jQuery Plugin Creation
Plugin jQuery, Design Patterns
Mojolicious - A new hope
J Query - Your First Steps
Matters of State
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it small - Getting to know the Slim PHP micro framework
jQuery Anti-Patterns for Performance & Compression
Childthemes ottawa-word camp-1919
Smarter Interfaces with jQuery (and Drupal)
Jquery Best Practices
jQuery Best Practice
How Kris Writes Symfony Apps
JQuery: Introduction
Automating boring tasks with Powershell
Maintainable JavaScript 2012
Task 1
Extending the WordPress REST API - Josh Pollock
Love and Loss: A Symfony Security Play
Ad

Viewers also liked (20)

PPT
Presentation1
PDF
[3 p] pianificare progettare-promuovere
PPTX
Tsea Pp
PPTX
Yritysostoperiaatteet - Aller Media
PDF
Hyvä paha peli #peliviikko
PPTX
Verkkokeskustelut ja brändit
PDF
Sometarinoita Suomesta - Kirjatori 21.4.2015
PDF
Sosiaalinen media = kissavideoita
PDF
Tips for Successful Crowdfunding from Heimo
PDF
Fact Sheet for Space Shuttle Endeavour's Final Mission STS-134
PDF
Apps for Real Estate Agents
PDF
Voice of the Customer in Travel
PPS
Estatuas Pelo Mundo
PDF
Koller Geneve MODE, LUXE & VINTAGE Bags MERCREDI 16 NOVEMBRE, 16h
PPTX
Editorial Calendar - Yes, You Need One. Here's Why.
PDF
Hoe fail ik als freelancer op sociale media ?
PPS
Perlas (Pearls)
PPTX
INBOUND Bold Talks: Dan Tyre
PPTX
Cuadro de gestion de proyectos
Presentation1
[3 p] pianificare progettare-promuovere
Tsea Pp
Yritysostoperiaatteet - Aller Media
Hyvä paha peli #peliviikko
Verkkokeskustelut ja brändit
Sometarinoita Suomesta - Kirjatori 21.4.2015
Sosiaalinen media = kissavideoita
Tips for Successful Crowdfunding from Heimo
Fact Sheet for Space Shuttle Endeavour's Final Mission STS-134
Apps for Real Estate Agents
Voice of the Customer in Travel
Estatuas Pelo Mundo
Koller Geneve MODE, LUXE & VINTAGE Bags MERCREDI 16 NOVEMBRE, 16h
Editorial Calendar - Yes, You Need One. Here's Why.
Hoe fail ik als freelancer op sociale media ?
Perlas (Pearls)
INBOUND Bold Talks: Dan Tyre
Cuadro de gestion de proyectos
Ad

Similar to jQuery Performance Rules (20)

KEY
jQuery: Tips, tricks and hints for better development and Performance
PPSX
jQuery - Doing it right
KEY
jQuery Performance Tips and Tricks (2011)
PDF
jQuery quick tips
PPT
jQuery Tips Tricks Trivia
PPTX
Jquery optimization-tips
KEY
Advanced jQuery
PDF
jQuery - 10 Time-Savers You (Maybe) Don't Know
PDF
06 jQuery #burningkeyboards
PPTX
Java script performance tips
PPTX
Unobtrusive javascript with jQuery
KEY
jQuery Anti-Patterns for Performance
KEY
Bcblackpool jquery tips
PPTX
jQuery Performance Tips and Tricks
PPT
Javascript and Jquery Best practices
PPTX
5 Tips for Better JavaScript
PDF
DrupalCon jQuery
PPT
Enhance Web Performance
PPT
High Performance Ajax Applications 1197671494632682 2
PPT
High Performance Ajax Applications
jQuery: Tips, tricks and hints for better development and Performance
jQuery - Doing it right
jQuery Performance Tips and Tricks (2011)
jQuery quick tips
jQuery Tips Tricks Trivia
Jquery optimization-tips
Advanced jQuery
jQuery - 10 Time-Savers You (Maybe) Don't Know
06 jQuery #burningkeyboards
Java script performance tips
Unobtrusive javascript with jQuery
jQuery Anti-Patterns for Performance
Bcblackpool jquery tips
jQuery Performance Tips and Tricks
Javascript and Jquery Best practices
5 Tips for Better JavaScript
DrupalCon jQuery
Enhance Web Performance
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation theory and applications.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Tartificialntelligence_presentation.pptx
PDF
cuic standard and advanced reporting.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Getting Started with Data Integration: FME Form 101
PPTX
A Presentation on Artificial Intelligence
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Big Data Technologies - Introduction.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Electronic commerce courselecture one. Pdf
SOPHOS-XG Firewall Administrator PPT.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation theory and applications.pdf
Empathic Computing: Creating Shared Understanding
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Tartificialntelligence_presentation.pptx
cuic standard and advanced reporting.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Getting Started with Data Integration: FME Form 101
A Presentation on Artificial Intelligence
The Rise and Fall of 3GPP – Time for a Sabbatical?
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Big Data Technologies - Introduction.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Network Security Unit 5.pdf for BCA BBA.
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton

jQuery Performance Rules

  • 1. jQuery Performance Rules I hear...I forget I see...and I remember I do...and I understand - Ancient Chinese Proverb
  • 2. No best practices Browser has to do more work Impacts performance – CPU utilization
  • 3. 1. Always Descend From an #id <div id=&quot;content&quot;> <form method=&quot;post&quot; action=&quot;/&quot;> <h2>Traffic Light</h2> <ul id=&quot;traffic_light&quot;> <li><input type=&quot;radio&quot; class=&quot;on&quot; name=&quot;light&quot; value=&quot;red&quot; /> Red</li> <li><input type=&quot;radio&quot; class=&quot;off&quot; name=&quot;light&quot; value=&quot;yellow&quot; /> Yellow</li> <li><input type=&quot;radio&quot; class=&quot;off&quot; name=&quot;light&quot; value=&quot;green&quot; /> Green</li> </ul> <input class=&quot;button&quot; id=&quot;traffic_button&quot; type=&quot;submit&quot; value=&quot;Go&quot; /> </form> </div> Selecting the button like this is slower: var traffic_button = $('#content .button'); Instead, select the button directly: var traffic_button = $('#traffic_button'); When selecting multiple elements, always descend from the closest parent ID. var traffic_lights = $('#traffic_light input');
  • 4. 2. Use Tags Before Classes <div id=&quot;content&quot;> <form method=&quot;post&quot; action=&quot;/&quot;> <h2>Traffic Light</h2> <ul id=&quot;traffic_light&quot;> <li><input type=&quot;radio&quot; class=&quot;on&quot; name=&quot;light&quot; value=&quot;red&quot; /> Red</li> <li><input type=&quot;radio&quot; class=&quot;off&quot; name=&quot;light&quot; value=&quot;yellow&quot; /> Yellow</li> <li><input type=&quot;radio&quot; class=&quot;off&quot; name=&quot;light&quot; value=&quot;green&quot; /> Green</li> </ul> <input class=&quot;button&quot; id=&quot;traffic_button&quot; type=&quot;submit&quot; value=&quot;Go&quot; /> </form> </div> Always prefix a class with a tag name (and remember to descend from an ID): var active_light = $('#traffic_light input.on');
  • 5. 3. Cache jQuery Objects Cache jQuery objects to a variable, never repeat a jQuery selection in your application. For example, never do this… $('#traffic_light input.on).bind('click', function(){...}); $('#traffic_light input.on).css('border', '3px dashed yellow'); $('#traffic_light input.on).css('background-color', 'orange'); $('#traffic_light input.on).fadeIn('slow'); Instead, first save the object to a local variable, and continue your operations: var $active_light = $('#traffic_light input.on'); $active_light.bind('click', function(){...}); $active_light.css('border', '3px dashed yellow'); $active_light.css('background-color', 'orange'); $active_light.fadeIn('slow'); Storing jQuery results for later $my = { head : $('head'), traffic_light : $('#traffic_light'), traffic_button : $('#traffic_button') };
  • 6. 4. Harness the Power of Chaining This allows us to write less code, making our JavaScript more lightweight. var $active_light = $('#traffic_light input.on'); $active_light.bind('click', function(){...}) .css('border', '3px dashed yellow') .css('background-color', 'orange') .fadeIn('slow');
  • 7. 5. Use Sub-queries jQuery allows us to run additional selector operations on a wrapped set. This reduces performance overhead on subsequent selections since we already grabbed and stored the parent object in a local variable. var $traffic_light = $('#traffic_light'), $active_light = $traffic_light.find('input.on'), $inactive_lights = $traffic_light.find('input.off'); Tip: You can declare multiple local variables by separating them with commas – save those bytes!
  • 8. 6. Limit Direct DOM Manipulation The basic idea here is to create exactly what you need in memory, and then update the DOM. This is not a jQuery best practice, but a must for efficient JavaScript. For example, if you need to dynamically create a list of elements, do not do this: var top_100_list = [...], // assume this has 100 unique strings $mylist = $('#mylist'); // jQuery selects our <ul> element for (var i=0, l=top_100_list.length; i<l; i++) { $mylist.append('<li>' + top_100_list[i] + '</li>'); } Instead, we want to create the entire set of elements in a string before inserting into the DOM: var top_100_list = [...], // assume this has 100 unique strings $mylist = $('#mylist'), // jQuery selects our <ul> element top_100_li = &quot;&quot;; // This will store our list items for (var i=0, l=top_100_list.length; i<l; i++) { top_100_li += '<li>' + top_100_list[i] + '</li>'; } $mylist.html(top_100_li);
  • 9. 7. Leverage Event Delegation (a.k.a. Bubbling) Every event (e.g. click, mouseover, etc.) in JavaScript “bubbles” up the DOM tree to parent elements. This is incredibly useful when we want many elements (nodes) to call the same function. A binding like this is inefficient. $('#entryform input).bind('focus', function(){ $(this).addClass('selected'); }).bind('blur', function(){ $(this).removeClass('selected'); }); Instead, we should listen for the focus and blur events at the parent level. $('#entryform).bind('focus', function(e){ var cell = $(e.target); // e.target grabs the node that triggered the event. cell.addClass('selected'); }).bind('blur', function(e){ var cell = $(e.target); cell.removeClass('selected'); }); The parent node acts as a dispatcher and can then do work based on what target element triggered the event.
  • 10. 8. Eliminate Query Waste Although jQuery fails nicely if it does not find any matching elements, it still takes time to look for them. If you have one global JavaScript for your entire site, it may be tempting to throw every one of your jQuery functions into $(document).ready(function(){ // all my glorious code }) Your Global JS library would look something like this: var mylib = { article_page : { init : function() { // Article page specific jQuery functions. } }, traffic_light : { init : function() { // Traffic light specific jQuery functions. } } }
  • 11. 9. Defer to $(window).load Although $(document).ready is incredibly useful, it occurs during page render while objects are still downloading. If you notice your page stalling while loading, all those $(document).ready functions could be the reason why. You can reduce CPU utilization during the page load by binding your jQuery functions to the $(window).load event, which occurs after all objects called by the HTML (including <iframe> content) have downloaded. $(window).load(function(){ // jQuery functions to initialize after the page has loaded. }); Superfluous functionality such as drag and drop, binding visual effects and animations, pre-fetching hidden images, etc., are all good candidates for this technique.
  • 12. Recap Always Descend From an #id Use Tags Before Classes Cache jQuery Objects Harness the Power of Chaining Use Sub-queries Limit Direct DOM Manipulation Leverage Event Delegation (a.k.a. Bubbling) Eliminate Query Waste Defer to $(window).load
  • 13.