jQuery Performance Rules

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Favorites, Groups & Events

    jQuery Performance Rules - Presentation Transcript

    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.  
    SlideShare Zeitgeist 2009

    + nagarajhublinagarajhubli Nominate

    custom

    347 views, 0 favs, 0 embeds more stats

    Rules that would help you in writing jQuery code in more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 347
      • 347 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 14
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories