Your SlideShare is downloading. ×
0
Unlearning and Relearning jQuery<br />Client-side Performance Optimization<br />Oct 14, 2010<br />1<br />Created for Magma...
Purpose and Audience<br />Purpose<br />Understand why client-side performance optimization is important<br />Better unders...
Why care about the performance of client-side code?<br />Myth: “It doesn’t run on my servers so it’s not important to the ...
Why use a JavaScript framework?<br />Deals with browser inconsistencies for you<br />You have to write a lot less code<br ...
Why jQuery and not Prototype?<br />Easier to use than Prototype<br />Usually results in fewer lines of code<br />jQuery ha...
Using jQuery with Ruby on Rails<br />For Rails 3<br />Use the Unobtrusive JavaScript library at http://github.com/rails/jq...
What you probably already know<br />You can access elements in a page using a CSS selector<br />$(‘#myDiv’) instead of doc...
What you may not know<br />Some selectors can be very slow<br />You don’t need to use $() every time you want to select an...
The DOM (Document Object Model)<br />Think of it as a JavaScript API for accessing HTML elements and manipulating them<br ...
The DOM (Document Object Model)<br />Terminology I’ll use<br /><ul><li>Descendent: All elements contained within that element
LINK and ANCHOR are descendents of DOCUMENT
TEXT and RADIO are descents of FORM
TEXT and RADIO are also descendents of DOCUMENT
Ancestor: The opposite of descendent
FORM is an ancestor of TEXT and RADIO
DOCUMENT is the ancestor of FORM, TEXT, RADIO, LINK, and ANCHOR
Parent: The direct ancestor of an element (only one)
FORM is the parent of TEXT and RADIO
DOCUMENT is the parent of LINK and ANCHOR
Children: The direct descendents of an element
TEXT and RADIO are children of FORM
TEXT and RADIO are not children of DOCUMENT (they are descendents)
LINK and ANCHOR are children of DOCUMENT</li></ul>Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performa...
Using Firebug to look at the DOM<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimiza...
The difference between DOM Ready and onload<br />You can’t access a DOM element until it has been fully loaded and rendere...
How do I choose?<br />Put application-critical JavaScript in a DOM Ready block<br />When you can’t use your application wi...
When do I need DOM Ready / onload?<br />Simple answer: when the browser loads your JavaScript before it loads the DOM elem...
Does that mean I don’t always need it?<br />Yes, but be careful. When in doubt, use DOM Ready or onload<br />This will wor...
Using DOM Ready and onload<br />Onload<br />function myFunction(){<br />  // your code<br />}<br />window.onload = myFunct...
Common mistake with DOM Ready<br />Don’t define methods in a Dom Ready block, just call them<br />Works<br />function myFu...
Getting elements faster<br />Always start with an ID<br />$(‘#myDiv’)<br />Behind the scenes, jQuery can use the native do...
Getting elements faster<br />Optimize selectors using the ‘right to left’ model<br />As of jQuery 1.3 this the method the ...
Cache your DOM lookups<br />A call to $() returns a valid jQuery object, so store it for later use<br />This is bad becaus...
Work with the most specific DOM element possible<br />$(‘#myDiv .myClass’) is much faster than $(‘.myClass’)<br />Use the ...
Use chaining<br />Remember that a call to $() returns a valid jQuery object, which means you can chain jQuery methods<br /...
When not to use chaining<br />Be careful chaining the DOM traversal methods<br />Doing so means that your application may ...
Avoid as much DOM manipulation as possible<br />Rendering changes to the DOM is very expensive, so do as few manipulations...
Avoid as much DOM manipulation as possible<br />It would be much more efficient to store all elements you wish to create i...
Avoid as much DOM manipulation as possible<br />It would be even more efficient if we wrap many individual elements in a s...
Avoid as much DOM manipulation as possible<br />Don’t like the idea of creating a string for your DOM elements?<br />Since...
Avoid as much DOM manipulation as possible<br />You can also improve performance of DOM manipulations by using the Documen...
Upcoming SlideShare
Loading in...5
×

Unlearning and Relearning jQuery - Client-side Performance Optimization

3,040

Published on

Published in: Technology, Design
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,040
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
33
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "Unlearning and Relearning jQuery - Client-side Performance Optimization"

  1. 1. Unlearning and Relearning jQuery<br />Client-side Performance Optimization<br />Oct 14, 2010<br />1<br />Created for Magma Rails 2010 - www.magmarails.com<br />
  2. 2. Purpose and Audience<br />Purpose<br />Understand why client-side performance optimization is important<br />Better understand jQuery and how to maximize performance when using it<br />Audience<br />Has a very basic understanding of client-side web development<br />JavaScript, HTML, CSS<br />Ideally, has used some JavaScript framework before<br />jQuery, Prototype, YUI, MooTools, etc.<br />If you haven’t specifically used jQuery before that’s fine. The API documentation will fill in the blanks later!<br />If you’ve never used a framework before that’s fine too, this will begin to make more sense later as you write your first jQuery application.<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />2<br />
  3. 3. Why care about the performance of client-side code?<br />Myth: “It doesn’t run on my servers so it’s not important to the speed of my application.”<br />Fact: Users of your website judge the performance of your application based on how long it takes for them to begin using it, not how long it takes to process and render a request on your servers<br />This is includes:<br />Number of requests for files to the server (this is a big deal)<br />Use sprites: http://css-tricks.com/css-sprites/<br />Compress JavaScript and CSS files into a single file of each type when possible: http://developer.yahoo.com/yui/compressor/<br />The total size of content download<br />The amount of time it takes to render the page<br />The amount of time it takes until the page is ready to be interacted with<br />How long it takes to process each interaction with the page<br />This means that perceived performance is just as important as actual performance! We’ll talk about techniques that apply to both<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />3<br />
  4. 4. Why use a JavaScript framework?<br />Deals with browser inconsistencies for you<br />You have to write a lot less code<br />Lots of community contribution and therefore a more stable core for your JavaScript application<br />You can upgrade to a newer version later and improve your application for free<br />Did I mention that you get to write less code?<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />4<br />
  5. 5. Why jQuery and not Prototype?<br />Easier to use than Prototype<br />Usually results in fewer lines of code<br />jQuery has a smaller footprint<br />By far the most popular JavaScript framework<br />About 28% of all websites on the internet use it<br />The big players use it (google, twitter, amazon, etc.)<br />This means more community support and more contribution to the open source code<br />Oct 14, 2010<br />5<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />
  6. 6. Using jQuery with Ruby on Rails<br />For Rails 3<br />Use the Unobtrusive JavaScript library at http://github.com/rails/jquery-ujs<br />In Rails 3 the JavaScript helpers no longer mix JS with your markup (this is a very good thing!) allowing us to easily swap out JS frameworks with just a single JS file<br />More instructions at http://joshhuckabee.com/jquery-rails-3<br />For older versions of Rails<br />Use the jRails plugin from http://github.com/aaronchi/jrails<br />Replaces the default helpers in Rails to output jQuery code instead of Prototype<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />6<br />
  7. 7. What you probably already know<br />You can access elements in a page using a CSS selector<br />$(‘#myDiv’) instead of document.getElementById(‘myDiv’)<br />In Prototype this would be $(‘myDiv’) since the $ method looks up an element based on its ID<br />$(‘.someClass’) gives you an array of all elements having a particular class<br />In Prototype this would be $$(‘.someClass’) since the $$ method is the one used for selecting elements via a CSS-style selector<br />You can do fun things like:<br />Show and hide elements on a page<br />$(‘#myDiv’).show()<br />$(‘#myDiv’).hide()<br />Make things happen when you click on an element<br />$(‘#myDiv’).click(function(){ alert(‘clicked!’) })<br />…and a bunch of other stuff too<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />7<br />
  8. 8. What you may not know<br />Some selectors can be very slow<br />You don’t need to use $() every time you want to select an element<br />You can chain jQuery method calls<br />Usually a good idea, but not always (more on this later)<br />You may be writing fewer lines of code with a JS framework but it can still make your application much slower if used improperly<br />This goes for all frameworks, including Prototype<br />jQuery !== JavaScript<br />jQuery is NOT all-powerful!<br />You still need to understand how JavaScript works without it!<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />8<br />
  9. 9. The DOM (Document Object Model)<br />Think of it as a JavaScript API for accessing HTML elements and manipulating them<br />Get an element with a particular ID<br />document.getElementById(‘myDiv’)<br />Redirect to another page<br />window.location = ‘http://example.com’<br />Get all elements with a particular tag name<br />document.getElementsByTagName(’div’);<br />All browsers support these<br />You want to favor jQuery use that directly maps to a built in DOM method because they will be the fastest<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />9<br />Image courtesy of John M. Kennedy T. http://en.wikipedia.org/wiki/File:JKDOM.SVG<br />
  10. 10. The DOM (Document Object Model)<br />Terminology I’ll use<br /><ul><li>Descendent: All elements contained within that element
  11. 11. LINK and ANCHOR are descendents of DOCUMENT
  12. 12. TEXT and RADIO are descents of FORM
  13. 13. TEXT and RADIO are also descendents of DOCUMENT
  14. 14. Ancestor: The opposite of descendent
  15. 15. FORM is an ancestor of TEXT and RADIO
  16. 16. DOCUMENT is the ancestor of FORM, TEXT, RADIO, LINK, and ANCHOR
  17. 17. Parent: The direct ancestor of an element (only one)
  18. 18. FORM is the parent of TEXT and RADIO
  19. 19. DOCUMENT is the parent of LINK and ANCHOR
  20. 20. Children: The direct descendents of an element
  21. 21. TEXT and RADIO are children of FORM
  22. 22. TEXT and RADIO are not children of DOCUMENT (they are descendents)
  23. 23. LINK and ANCHOR are children of DOCUMENT</li></ul>Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />10<br />Note: Examples are for the image to the right, not true for all pages<br />Image courtesy of John M. Kennedy T. http://en.wikipedia.org/wiki/File:JKDOM.SVG<br />
  24. 24. Using Firebug to look at the DOM<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />11<br />Firebug is a free extension for Firefox: http://getfirebug.com/Webkit browsers (like Safari and Chrome) have similar built-in functionality.<br />
  25. 25. The difference between DOM Ready and onload<br />You can’t access a DOM element until it has been fully loaded and rendered by the browser<br />onload occurs after everything on the page has been loaded<br />HTML<br />Stylesheets<br />JavaScript (including 3rd party!)<br />Images<br />Content of iframes<br />Comes with the browser<br />window.onload = myFunction;<br /><body onload=“myFunction();”><br />DOM Ready occurs when the document has been processed and all DOM objects are ready for manipulation<br />Doesn’t wait for assets since they aren’t part of the DOM<br />jQuery and Prototype give you this functionality<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />12<br />
  26. 26. How do I choose?<br />Put application-critical JavaScript in a DOM Ready block<br />When you can’t use your application without it<br />Example: critical event listeners<br />$(‘#myButton’).click(loadImportantForm);<br />Use onload for anything non-critical<br />Deferring to onload is a good idea when possible because too much code in DOM Ready can cause the rendering of your page to stall, adding additional time until the user can interact with it<br />Example: initializing animations<br />$(‘#myDiv’).hover(sillyFadeOver, sillyFadeOut);<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />13<br />
  27. 27. When do I need DOM Ready / onload?<br />Simple answer: when the browser loads your JavaScript before it loads the DOM elements you need<br />When you define your JavaScript in external files<br />Usually you include these in the header. This means that the JavaScript file is fully loaded an begins to execute before the browser begins to load the body of your document.<br />Sometimes you also include JS files within the body of your document. In this case you don’t know when the file will be ready to execute. Could happen before your DOM is ready or after it.<br />When you use inline JavaScript before all required elements have been loaded<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />14<br />
  28. 28. Does that mean I don’t always need it?<br />Yes, but be careful. When in doubt, use DOM Ready or onload<br />This will work<br /><a id=“myAnchor” href=“#”>click me if you can</a><br /><script>document.getElementById(‘myAnchor’);</script><br />This will not<br /><script>document.getElementById(‘myAnchor’);</script><br /><a id=“myAnchor” href=“#”>click me if you can</a><br />This will work in some browsers but IE < 8 will have a fit<br /><body> <br /> <div><br />   <script type="text/javascript"> <br />varnewElem = document.createElement(’div'); <br />    document.body.appendChild(newElem); <br />   </script><br /> </div><br /></body> <br />(so don’t try to use element before it has been closed)<br />This applies to jQuery syntax as well<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />15<br />
  29. 29. Using DOM Ready and onload<br />Onload<br />function myFunction(){<br /> // your code<br />}<br />window.onload = myFunction;// replaces onload with this function, so can only have this once<br />Onload (jQuery style)<br />$(window).load(function(){ // can have multiple on a page<br />// your code<br />});<br />DOM Ready<br />jQuery only and can have multiple DOM Ready blocks on a page<br />Longer format<br />$(document).ready(function(){<br /> // your code<br />});<br />Short version<br />$(function(){<br /> // your code<br />});<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />16<br />
  30. 30. Common mistake with DOM Ready<br />Don’t define methods in a Dom Ready block, just call them<br />Works<br />function myFunction(){<br /> // your code<br />}<br />$(document).ready(function(){<br />myFunction();<br />});<br />Doesn’t work<br />$(document).ready(function(){<br /> function myFunction(){<br /> // your code<br /> }<br />myFunction();<br />});<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />17<br />
  31. 31. Getting elements faster<br />Always start with an ID<br />$(‘#myDiv’)<br />Behind the scenes, jQuery can use the native document.getElementById() which is very fast<br />Fastest way to get a DOM element<br />Avoid the class selector on a large DOM node<br />$(‘.myClass’)<br />Very slow over a large DOM node<br />No native DOM call common to all browsers<br />Use a tag name when possible<br />$(‘div.myClass’) is much faster than $(‘.myClass’)<br />Uses document.getElementsByTagName() behind the scenes<br />But remember that ID is the fastest so $(‘div#myDiv’) is actually slower than $(‘#myDiv’)<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />18<br />
  32. 32. Getting elements faster<br />Optimize selectors using the ‘right to left’ model<br />As of jQuery 1.3 this the method the selector engine uses<br />This means the most specific (right-most) selector is found first and then its ancestors are checked starting on the left<br />Make your right-most selector very efficient<br />Example<br />$(‘.myClassdiv.otherClass’) is actually more efficient than<br />$(‘div.myClass .otherClass’)<br />However, descending from an ID is still the fastest:<br />$(‘#myDivdiv.otherClass’)<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />19<br />
  33. 33. Cache your DOM lookups<br />A call to $() returns a valid jQuery object, so store it for later use<br />This is bad because each line does a DOM lookup<br />$(‘#myDiv .myClass’).click(myFunc);<br />$(‘#myDiv .myClass’).css(‘width’, ‘250px’);<br />$(‘#myDiv .myClass’).css(‘color’, ‘red’);<br />This is much better<br />varmyStuff = $(‘#myDiv .myClass’);<br />myStuff.click(myFunc);<br />myStuff.css(‘width’, ‘250px’);<br />myStuff.css(‘color’, ‘red’);<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />20<br />
  34. 34. Work with the most specific DOM element possible<br />$(‘#myDiv .myClass’) is much faster than $(‘.myClass’)<br />Use the find() jQuery method to search for matching elements within your cached object<br />varmyDiv = $(‘#myDiv’);<br />myDiv.find(‘.myClass’).hide();<br />myDiv.find(‘input’).click(myFun);<br />A lot of times it makes sense to cache the main elements of your page up front and use them later<br />content = $(‘#content’);<br />sidebar = content.find(‘#sidebar’);<br />article = content.find(‘#article’);<br />commentWrapper = article.find(‘#comments’);<br />comments = commentWrapper.find(‘div.comment’);<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />21<br />
  35. 35. Use chaining<br />Remember that a call to $() returns a valid jQuery object, which means you can chain jQuery methods<br />You can shorten the previous example:<br />$(‘#myDiv .myClass’).click(myFunc);<br />$(‘#myDiv .myClass’).css(‘width’, ‘250px’);<br />$(‘#myDiv .myClass’).css(‘color’, ‘red’);<br />To the lighter-weight:<br />$(‘#myDiv .myClass’).click(myFunc).css(‘width’, ‘250px’).css(‘color’, ‘red’);<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />22<br />
  36. 36. When not to use chaining<br />Be careful chaining the DOM traversal methods<br />Doing so means that your application may be too dependent on the DOM structure<br />Example of what not to do:<br />$(‘#myDiv’).parent().parent(); // fails if you add another element surrounding this one<br />Potential alternatives:<br />$(‘#myDiv’).parents(‘someTag’)<br />$(‘#myDiv’).parents(‘.someClass’)<br />Not about performance, but about writing good code<br />Yes, the DOM structure still matters in the last two examples but it isn’t so rigid that you can’t add or remove elements in between<br />And yes, the last two examples may be a little slower but not so much that it’s worth writing unsafe code<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />23<br />
  37. 37. Avoid as much DOM manipulation as possible<br />Rendering changes to the DOM is very expensive, so do as few manipulations as possible<br />Example of what not to do:<br /><div id=“myDiv”></div><br /><script><br />for(vari=0; i < 100; i++){<br /> $(‘#myDiv’).append(‘<a href=“#”>link</a>’); // The browser has to re-render this and any other effected elements at each iteration of the loop<br />}<br /></script><br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />24<br />
  38. 38. Avoid as much DOM manipulation as possible<br />It would be much more efficient to store all elements you wish to create in a string and then insert them one time:<br /><div id=“myDiv”></div><br /><script><br />myLinks = ‘’;<br />for(vari=0; i < 100; i++){<br />myLinks = myLinks + ‘<a href=“#”>link</a>’;<br />}<br />$(‘#myDiv’).append(myLinks); // this is the only DOM manipulation<br /></script><br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />25<br />
  39. 39. Avoid as much DOM manipulation as possible<br />It would be even more efficient if we wrap many individual elements in a single element and then insert that in the DOM:<br /><div id=“myDiv”></div><br /><script><br />myLinks = ‘<div id=“myDiv”>’;<br />for(vari=0; i < 100; i++){<br />myLinks = myLinks + ‘<a href=“#”>link</a>’;<br />}<br />myLinks = myLinks + ‘</div>’;<br />$(‘#myDiv’).replaceWith(myLinks); // instead of putting a string of 100 elements in this div we are replacing a single DOM node<br /></script><br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />26<br />
  40. 40. Avoid as much DOM manipulation as possible<br />Don’t like the idea of creating a string for your DOM elements?<br />Since rendering is the most expensive part, use the clone() jQuery method to make a copy of the DOM object that you can manipulate without being rendered and then insert that object into the DOM when finished<br /><div id=“myDiv”></div><br /><script><br />clonedDiv = $(‘#myDiv’).clone();<br />for(vari=0; i < 100; i++){<br />clonedDiv.append(‘<a href=“#”>link</a>’); // clonedDiv is not visible on the page so manipulating it doesn’t cause the browser to re-render<br />}<br />$(‘#myDiv’).replaceWith(clonedDiv); // still the only time re-rendering occurs<br /></script><br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />27<br />
  41. 41. Avoid as much DOM manipulation as possible<br />You can also improve performance of DOM manipulations by using the DocumentFragment object<br />DocumentFragment is a lightweight Document object you can create, manipulate and then insert into the DOM later (much like the previous example)<br />More information at: http://www.devguru.com/technologies/xmldom/quickref/obj_documentFragment.html<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />28<br />
  42. 42. Event delegation<br />Events in jQuery “bubble” up to their parent DOM elements unless you tell them not to<br />You can use this to your advantage by creating a single event listener on a parent object and letting that listener determine which of its children triggered the event<br />This is much more efficient than creating a many listeners on individual elements<br />If you’re only binding one or two event listeners then this method isn’t really necessary<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />29<br />
  43. 43. Event delegation<br />Let’s say you have a div with 100 anchor tags and you want to hide the anchor when it’s clicked<br />Instead of:<br />$(‘#myDiva’).bind(‘click’, function(){<br /> $(this).hide();<br />});<br />Do this:<br />$(‘#myDiv’).bind(‘click’, function(e){<br />if(e.target.nodeName.toLowerCase() === 'a'){<br /> $(e.target).hide()<br /> }<br />});<br />e is the Event object<br />Notice that e.target returns the actual DOM node, not a jQuery object, so you need to pass it to $() to get jQuery functionality<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />30<br />
  44. 44. jQuery.delegate()<br />This is the same example using jQuery’s built in event delegation method (1.4.2 and above)<br />$('#myDiv').delegate('a', 'click', function(e){<br /> $(this).hide();<br />});<br />Tip: for this and the last example, use e.preventDefault() to prevent the default action of the event. In this case, following the hyperlink:<br />$('#myDiv').delegate('a', 'click', function(e){<br />e.preventDefault(); <br /> $(this).hide();<br />});<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />31<br />
  45. 45. Lazy-loading assets<br />Load the bare minimum up front and load the rest as needed<br />Initial load and rendering of the page is much faster, allowing the user to interact with the page as quickly as possible<br />Works well in many cases but sometimes waiting for something to load after the user begins to interact with the page is more frustrating, so choose wisely when it’s appropriate<br />An excellent choice for non-critical 3rd party tracking scripts, especially ones that are notorious slow<br />Can apply to JavaScript files, images, even CSS<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />32<br />
  46. 46. Lazy-loading assets<br />Method 1: document.write()<br />Can also apply this method to other types of assets such as images and CSS<br /><script><br />document.write('<script src="', ’someScript.js', '" type="text/javascript"></script>');<br /></script><br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />33<br />
  47. 47. Lazy-loading assets<br />Method 2: Change the src property of an existing script tag<br />This example is just for JavaScript but you could do something similar for other assets<br /><script id=”lazy" type="text/JavaScript"></script><br /><script><br />document.getElementById(’lazy').src = ‘someScript.js';<br /></script><br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />34<br />
  48. 48. Lazy-loading assets<br />Method 3: Use AJAX<br />Applies to any type of asset<br />Just add an AJAX call on DOM Ready to grab what you need<br />Check out the jQuery documentation on using AJAX: http://api.jquery.com/category/ajax/<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />35<br />
  49. 49. Lazy-loading assets<br />Method 4: Use the Lazy Load jQuery plugin: http://www.appelsiini.net/projects/lazyload<br />When you want to lazy load images on a very long page<br />Let’s you load images visible in the browser first and delay loading of images “below the fold” (below the current browser view)<br />Simplest example: <br />$("img").lazyload(); // causing images below the fold to be lazy loaded<br />Start loading images when they are 200px below the fold:<br />$("img").lazyload({ threshold : 200 });<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />36<br />
  50. 50. Unobtrusive JavaScript<br />Keep JavaScript in external files and avoid inline JavaScript (Rails 3 does it!)<br />Less code for the browser to load and interpret while rendering<br />JavaScript in external files can be cached by the browser. Inline JavaScript can’t be cached<br />Avoid:<br /><a href=“#” onclick=“myFunc();”>run myFunc</a><br />In favor of:<br /><a href=“#” id=“myLink”>run myFunc</a><br />$(‘#myLink’).bind(‘click’, myFunc); // in external file on DOM Ready<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />37<br />
  51. 51. Unobtrusive JavaScript<br />Rails 3 is a great inspiration for more advanced uses<br />Uses custom attributes to indentify what events to bind on elements<br />Rails helper code:<br /><%= link_to "delete", domain_path(@domain), :method => :delete, :confirm => "Are you sure?" %><br />In Rails 2 this outputs a real mess:<br /><a href="/domains/1" class="destroy" onclick="if (confirm('Are you sure?')) { varf = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;varm = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);vars = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'pKvg9hsnQ33uk='); f.appendChild(s);f.submit(); };return false;">delete</a><br />In Rails 3 the markup just looks like this:<br /><a href="/domains/1" data-confirm="Are you sure?" data-method="delete" rel="nofollow">delete</a><br />An external JavaScript file (remember jquery-ujs?) uses the attributes and binds the appropriate JavaScript to the element<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />38<br />Examples from http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/<br />
  52. 52. Storing data on DOM objects<br />Sometimes you need to store extra information about an element to improve efficiency, keep yourself from having to pass a bunch of variables through method calls, etc.<br />It’s tempting to do one of the following:<br />$(‘#myElement’).attr(‘rel’, ‘some data’); // improper use of attribute<br />var data = $(‘#myElement’).attr(‘rel’);<br />$(‘#hiddenInput’).val(‘some data’); // unnecessary form data<br />var data = $(‘#hiddenInput’).val();<br />jQuery gives you a much nicer alternative:<br />$(‘#myElement’).data(‘key’, ‘value’);<br />var data = $(‘#myElement’).data(‘key’);<br />Note: you can also store data on a DOM object directly using standard object syntax since a DOM object is the same as any other object. Just don’t store it on a jQuery object unless you use data()<br />varelem = $(‘#myElement’).get(0);<br />elem.foo = ‘bar’;<br />alert(elem.foo);<br />But data() is safer so you generally just want to use that<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />39<br />
  53. 53. Use for instead of each()<br />The native for loop is much faster than jQuery’s each() iterator so use it when possible for large arrays<br />Instead of:<br />$.each (array, function (i) { <br /> // do something with array[i]<br />});<br />The same can be done with a native for loop:<br />for (vari=0;i<array.length; i++) { <br /> // do something with array[i]<br />}<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />40<br />
  54. 54. Use short variable names and create aliases<br />Reduces overall size of file, especially if not minified<br />Only useful when these items are used frequently in a large JS application<br />Does reduce code readability so good minification may be a better option in many cases, but some of these may not be minified so watch out<br />varw = window,<br />l = w.location,<br />d = document,<br />t = true,<br />f = false,<br />n = null,<br /> M = Math,<br />o = "object",<br /> a = "array",<br />s = "string”, <br />u = "undefined";<br />l = ‘http://jonathandean.com’; // redirect to another page<br />if(myVar == f || myVar == n) // test if myVar is false or null<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />41<br />
  55. 55. Other client-side performance tips<br />Make the fewest number of requests to the server as possible<br />Each request adds overhead and additional time to load<br />Combine multiple small images into a single sprite<br />Combine JS and CSS into a single file of each type when possible<br />Don’t load a file you don’t need<br />Compress JS and CSS to remove whitespace characters and shorten long variable and method names<br />You don’t necessarily want to create “packed” files<br />These files will have the smallest total size<br />However, the browser needs to read in the entire file and parse it before it can be used. The parsing step is not cached and adds overhead to each page load. Often the benefit does not outweigh the cost<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />42<br />
  56. 56. Download for later<br />You can find these slides sometime tomorrow at http://www.jonathandean.com/2010/10/unlearning-and-relearning-jquery-client-side-performance-optimization/<br />The short URL is http://tinyurl.com/jquery-magma<br />Check http://jonathandean.com soon for an HTML version of the presentation (after a few more caguamas and a long flight home!)<br />Oct 14, 2010<br />Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com<br />43<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×