SlideShare uma empresa Scribd logo
1 de 41
Unlearning and Relearning jQuery Client-side Performance Optimization Oct 14, 2010 1 Created for Magma Rails 2010 - www.magmarails.com
Purpose and Audience Purpose Understand why client-side performance optimization is important Better understand jQuery and how to maximize performance when using it Audience Has a very basic understanding of client-side web development JavaScript, HTML, CSS Ideally, has used some JavaScript framework before jQuery, Prototype, YUI, MooTools, etc. If you haven’t specifically used jQuery before that’s fine. The API documentation will fill in the blanks later! 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. Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 2
Why care about the performance of client-side code? Myth: “It doesn’t run on my servers so it’s not important to the speed of my application.” 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 This is includes: Number of requests for files to the server (this is a big deal) Use sprites: http://css-tricks.com/css-sprites/ Compress JavaScript and CSS files into a single file of each type when possible: http://developer.yahoo.com/yui/compressor/ The total size of content download The amount of time it takes to render the page The amount of time it takes until the page is ready to be interacted with How long it takes to process each interaction with the page This means that perceived performance is just as important as actual performance! We’ll talk about techniques that apply to both Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 3
Why use a JavaScript framework? Deals with browser inconsistencies for you You have to write a lot less code Lots of community contribution and therefore a more stable core for your JavaScript application You can upgrade to a newer version later and improve your application for free Did I mention that you get to write less code? Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 4
Why jQuery and not Prototype? Easier to use than Prototype Usually results in fewer lines of code jQuery has a smaller footprint By far the most popular JavaScript framework About 28% of all websites on the internet use it The big players use it (google, twitter, amazon, etc.) This means more community support and more contribution to the open source code Oct 14, 2010 5 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com
Using jQuery with Ruby on Rails For Rails 3 Use the Unobtrusive JavaScript library at http://github.com/rails/jquery-ujs 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 More instructions at http://joshhuckabee.com/jquery-rails-3 For older versions of Rails Use the jRails plugin from http://github.com/aaronchi/jrails Replaces the default helpers in Rails to output jQuery code instead of Prototype Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 6
What you probably already know You can access elements in a page using a CSS selector $(‘#myDiv’) instead of document.getElementById(‘myDiv’) In Prototype this would be $(‘myDiv’) since the $ method looks up an element based on its ID $(‘.someClass’) gives you an array of all elements having a particular class In Prototype this would be $$(‘.someClass’) since the $$ method is the one used for selecting elements via a CSS-style selector You can do fun things like: Show and hide elements on a page $(‘#myDiv’).show() $(‘#myDiv’).hide() Make things happen when you click on an element $(‘#myDiv’).click(function(){ alert(‘clicked!’) }) …and a bunch of other stuff too Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 7
What you may not know Some selectors can be very slow You don’t need to use $() every time you want to select an element You can chain jQuery method calls Usually a good idea, but not always (more on this later) You may be writing fewer lines of code with a JS framework but it can still make your application much slower if used improperly This goes for all frameworks, including Prototype jQuery !== JavaScript jQuery is NOT all-powerful! You still need to understand how JavaScript works without it! Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 8
The DOM (Document Object Model) Think of it as a JavaScript API for accessing HTML elements and manipulating them Get an element with a particular ID document.getElementById(‘myDiv’) Redirect to another page window.location = ‘http://example.com’ Get all elements with a particular tag name document.getElementsByTagName(’div’); All browsers support these You want to favor jQuery use that directly maps to a built in DOM method because they will be the fastest Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 9 Image courtesy of John M. Kennedy T. http://en.wikipedia.org/wiki/File:JKDOM.SVG
The DOM (Document Object Model) Terminology I’ll use ,[object Object]
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 DOCUMENTOct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 10 Note: Examples are for the image to the right, not true for all pages Image courtesy of John M. Kennedy T. http://en.wikipedia.org/wiki/File:JKDOM.SVG
Using Firebug to look at the DOM Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 11 Firebug is a free extension for Firefox: http://getfirebug.com/Webkit browsers (like Safari and Chrome) have similar built-in functionality.
The difference between DOM Ready and onload You can’t access a DOM element until it has been fully loaded and rendered by the browser onload occurs after everything on the page has been loaded HTML Stylesheets JavaScript (including 3rd party!) Images Content of iframes Comes with the browser window.onload = myFunction; <body onload=“myFunction();”> DOM Ready occurs when the document has been processed and all DOM objects are ready for manipulation Doesn’t wait for assets since they aren’t part of the DOM jQuery and Prototype give you this functionality Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 12
How do I choose? Put application-critical JavaScript in a DOM Ready block When you can’t use your application without it Example: critical event listeners $(‘#myButton’).click(loadImportantForm); Use onload for anything non-critical 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 Example: initializing animations $(‘#myDiv’).hover(sillyFadeOver, sillyFadeOut); Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 13
When do I need DOM Ready / onload? Simple answer: when the browser loads your JavaScript before it loads the DOM elements you need When you define your JavaScript in external files 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. 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. When you use inline JavaScript before all required elements have been loaded Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 14
Does that mean I don’t always need it? Yes, but be careful. When in doubt, use DOM Ready or onload This will work <a id=“myAnchor” href=“#”>click me if you can</a> <script>document.getElementById(‘myAnchor’);</script> This will not <script>document.getElementById(‘myAnchor’);</script> <a id=“myAnchor” href=“#”>click me if you can</a> This will work in some browsers but IE < 8 will have a fit <body>    <div>     <script type="text/javascript">  varnewElem = document.createElement(’div');      document.body.appendChild(newElem);      </script>   </div> </body>  (so don’t try to use element before it has been closed) This applies to jQuery syntax as well Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 15
Using DOM Ready and onload Onload function myFunction(){   // your code } window.onload = myFunction;// replaces onload with this function, so can only have this once Onload (jQuery style) $(window).load(function(){ // can have multiple on a page // your code }); DOM Ready jQuery only and can have multiple DOM Ready blocks on a page Longer format $(document).ready(function(){   // your code }); Short version $(function(){   // your code }); Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 16
Common mistake with DOM Ready Don’t define methods in a Dom Ready block, just call them Works function myFunction(){   // your code } $(document).ready(function(){ myFunction(); }); Doesn’t work $(document).ready(function(){   function myFunction(){     // your code   } myFunction(); }); Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 17
Getting elements faster Always start with an ID $(‘#myDiv’) Behind the scenes, jQuery can use the native document.getElementById() which is very fast Fastest way to get a DOM element Avoid the class selector on a large DOM node $(‘.myClass’) Very slow over a large DOM node No native DOM call common to all browsers Use a tag name when possible $(‘div.myClass’) is much faster than $(‘.myClass’) Uses document.getElementsByTagName() behind the scenes But remember that ID is the fastest so $(‘div#myDiv’) is actually slower than $(‘#myDiv’) Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 18
Getting elements faster Optimize selectors using the ‘right to left’ model As of jQuery 1.3 this the method the selector engine uses This means the most specific (right-most) selector is found first and then its ancestors are checked starting on the left Make your right-most selector very efficient Example $(‘.myClassdiv.otherClass’) is actually more efficient than $(‘div.myClass .otherClass’) However, descending from an ID is still the fastest: $(‘#myDivdiv.otherClass’) Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 19
Cache your DOM lookups A call to $() returns a valid jQuery object, so store it for later use This is bad because each line does a DOM lookup $(‘#myDiv .myClass’).click(myFunc); $(‘#myDiv .myClass’).css(‘width’, ‘250px’); $(‘#myDiv .myClass’).css(‘color’, ‘red’); This is much better varmyStuff = $(‘#myDiv .myClass’); myStuff.click(myFunc); myStuff.css(‘width’, ‘250px’); myStuff.css(‘color’, ‘red’); Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 20
Work with the most specific DOM element possible $(‘#myDiv .myClass’) is much faster than $(‘.myClass’) Use the find() jQuery method to search for matching elements within your cached object varmyDiv = $(‘#myDiv’); myDiv.find(‘.myClass’).hide(); myDiv.find(‘input’).click(myFun); A lot of times it makes sense to cache the main elements of your page up front and use them later content = $(‘#content’); sidebar = content.find(‘#sidebar’); article = content.find(‘#article’); commentWrapper = article.find(‘#comments’); comments = commentWrapper.find(‘div.comment’); Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 21
Use chaining Remember that a call to $() returns a valid jQuery object, which means you can chain jQuery methods You can shorten the previous example: $(‘#myDiv .myClass’).click(myFunc); $(‘#myDiv .myClass’).css(‘width’, ‘250px’); $(‘#myDiv .myClass’).css(‘color’, ‘red’); To the lighter-weight: $(‘#myDiv .myClass’).click(myFunc).css(‘width’, ‘250px’).css(‘color’, ‘red’); Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 22
When not to use chaining Be careful chaining the DOM traversal methods Doing so means that your application may be too dependent on the DOM structure Example of what not to do: $(‘#myDiv’).parent().parent(); // fails if you add another element surrounding this one Potential alternatives: $(‘#myDiv’).parents(‘someTag’) $(‘#myDiv’).parents(‘.someClass’) Not about performance, but about writing good code 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 And yes, the last two examples may be a little slower but not so much that it’s worth writing unsafe code Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 23
Avoid as much DOM manipulation as possible Rendering changes to the DOM is very expensive, so do as few manipulations as possible Example of what not to do: <div id=“myDiv”></div> <script> for(vari=0; i < 100; i++){   $(‘#myDiv’).append(‘<a href=“#”>link</a>’); // The browser has to re-render this and any other effected elements at each iteration of the loop } </script> Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 24
Avoid as much DOM manipulation as possible It would be much more efficient to store all elements you wish to create in a string and then insert them one time: <div id=“myDiv”></div> <script> myLinks = ‘’; for(vari=0; i < 100; i++){ myLinks = myLinks + ‘<a href=“#”>link</a>’; } $(‘#myDiv’).append(myLinks); // this is the only DOM manipulation </script> Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 25
Avoid as much DOM manipulation as possible It would be even more efficient if we wrap many individual elements in a single element and then insert that in the DOM: <div id=“myDiv”></div> <script> myLinks = ‘<div id=“myDiv”>’; for(vari=0; i < 100; i++){ myLinks = myLinks + ‘<a href=“#”>link</a>’; } myLinks = myLinks + ‘</div>’; $(‘#myDiv’).replaceWith(myLinks); // instead of putting a string of 100 elements in this div we are replacing a single DOM node </script> Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 26
Avoid as much DOM manipulation as possible Don’t like the idea of creating a string for your DOM elements? 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 <div id=“myDiv”></div> <script> clonedDiv = $(‘#myDiv’).clone(); for(vari=0; i < 100; i++){ clonedDiv.append(‘<a href=“#”>link</a>’); // clonedDiv is not visible on the page so manipulating it doesn’t cause the browser to re-render } $(‘#myDiv’).replaceWith(clonedDiv); // still the only time re-rendering occurs </script> Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 27
Avoid as much DOM manipulation as possible You can also improve performance of DOM manipulations by using the DocumentFragment object DocumentFragment  is a lightweight Document object you can create, manipulate and then insert into the DOM later (much like the previous example) More information at: http://www.devguru.com/technologies/xmldom/quickref/obj_documentFragment.html Oct 14, 2010 Unlearning and Relearning jQuery (Client-side performance Optimization) by Jonathan Dean - www.jonathandean.com 28

Mais conteúdo relacionado

Mais procurados

Vaadin Flow - JavaLand 2018
Vaadin Flow - JavaLand 2018Vaadin Flow - JavaLand 2018
Vaadin Flow - JavaLand 2018Peter Lehto
 
Building a Secure App with Google Polymer and Java / Spring
Building a Secure App with Google Polymer and Java / SpringBuilding a Secure App with Google Polymer and Java / Spring
Building a Secure App with Google Polymer and Java / Springsdeeg
 
Building Smart Workflows - Dan Diebolt
Building Smart Workflows - Dan DieboltBuilding Smart Workflows - Dan Diebolt
Building Smart Workflows - Dan DieboltQuickBase, Inc.
 
Vaadin DevDay 2017 - Web Components
Vaadin DevDay 2017 - Web ComponentsVaadin DevDay 2017 - Web Components
Vaadin DevDay 2017 - Web ComponentsPeter Lehto
 
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to DevelopmentWordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to DevelopmentEvan Mullins
 
Wicket Next (1.4/1.5)
Wicket Next (1.4/1.5)Wicket Next (1.4/1.5)
Wicket Next (1.4/1.5)jcompagner
 
State of jQuery '09
State of jQuery '09State of jQuery '09
State of jQuery '09jeresig
 
HTML CSS JavaScript jQuery Training
HTML CSS JavaScript jQuery TrainingHTML CSS JavaScript jQuery Training
HTML CSS JavaScript jQuery Trainingubshreenath
 
Moving from Web 1.0 to Web 2.0
Moving from Web 1.0 to Web 2.0Moving from Web 1.0 to Web 2.0
Moving from Web 1.0 to Web 2.0Estelle Weyl
 
Why and How to Use Virtual DOM
Why and How to Use Virtual DOMWhy and How to Use Virtual DOM
Why and How to Use Virtual DOMDaiwei Lu
 
Mobile Browser Internal (Blink Rendering Engine)
Mobile Browser Internal (Blink Rendering Engine)Mobile Browser Internal (Blink Rendering Engine)
Mobile Browser Internal (Blink Rendering Engine)Hyungwook Lee
 
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolution
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 RevolutionWebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolution
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolutionjuanjosanchezpenas
 
WebKit and Blink: open development powering the HTML5 revolution
WebKit and Blink: open development powering the HTML5 revolutionWebKit and Blink: open development powering the HTML5 revolution
WebKit and Blink: open development powering the HTML5 revolutionjuanjosanchezpenas
 
Build Reusable Web Components using HTML5 Web cComponents
Build Reusable Web Components using HTML5 Web cComponentsBuild Reusable Web Components using HTML5 Web cComponents
Build Reusable Web Components using HTML5 Web cComponentsGil Fink
 

Mais procurados (20)

Booting up with polymer
Booting up with polymerBooting up with polymer
Booting up with polymer
 
Vaadin Flow - JavaLand 2018
Vaadin Flow - JavaLand 2018Vaadin Flow - JavaLand 2018
Vaadin Flow - JavaLand 2018
 
Building a Secure App with Google Polymer and Java / Spring
Building a Secure App with Google Polymer and Java / SpringBuilding a Secure App with Google Polymer and Java / Spring
Building a Secure App with Google Polymer and Java / Spring
 
Building Smart Workflows - Dan Diebolt
Building Smart Workflows - Dan DieboltBuilding Smart Workflows - Dan Diebolt
Building Smart Workflows - Dan Diebolt
 
Introducing GWT Polymer (vaadin)
Introducing GWT Polymer (vaadin)Introducing GWT Polymer (vaadin)
Introducing GWT Polymer (vaadin)
 
Vaadin DevDay 2017 - Web Components
Vaadin DevDay 2017 - Web ComponentsVaadin DevDay 2017 - Web Components
Vaadin DevDay 2017 - Web Components
 
Html5 basics
Html5 basicsHtml5 basics
Html5 basics
 
GWT Reloaded
GWT ReloadedGWT Reloaded
GWT Reloaded
 
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to DevelopmentWordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
 
Wicket Next (1.4/1.5)
Wicket Next (1.4/1.5)Wicket Next (1.4/1.5)
Wicket Next (1.4/1.5)
 
State of jQuery '09
State of jQuery '09State of jQuery '09
State of jQuery '09
 
Swf search final
Swf search finalSwf search final
Swf search final
 
HTML CSS JavaScript jQuery Training
HTML CSS JavaScript jQuery TrainingHTML CSS JavaScript jQuery Training
HTML CSS JavaScript jQuery Training
 
Moving from Web 1.0 to Web 2.0
Moving from Web 1.0 to Web 2.0Moving from Web 1.0 to Web 2.0
Moving from Web 1.0 to Web 2.0
 
Web Component
Web ComponentWeb Component
Web Component
 
Why and How to Use Virtual DOM
Why and How to Use Virtual DOMWhy and How to Use Virtual DOM
Why and How to Use Virtual DOM
 
Mobile Browser Internal (Blink Rendering Engine)
Mobile Browser Internal (Blink Rendering Engine)Mobile Browser Internal (Blink Rendering Engine)
Mobile Browser Internal (Blink Rendering Engine)
 
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolution
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 RevolutionWebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolution
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolution
 
WebKit and Blink: open development powering the HTML5 revolution
WebKit and Blink: open development powering the HTML5 revolutionWebKit and Blink: open development powering the HTML5 revolution
WebKit and Blink: open development powering the HTML5 revolution
 
Build Reusable Web Components using HTML5 Web cComponents
Build Reusable Web Components using HTML5 Web cComponentsBuild Reusable Web Components using HTML5 Web cComponents
Build Reusable Web Components using HTML5 Web cComponents
 

Destaque

TYPO3 as Mobile Application Management System
TYPO3 as Mobile Application Management SystemTYPO3 as Mobile Application Management System
TYPO3 as Mobile Application Management SystemFedir RYKHTIK
 
DevOps for TYPO3 Teams and Projects
DevOps for TYPO3 Teams and ProjectsDevOps for TYPO3 Teams and Projects
DevOps for TYPO3 Teams and ProjectsFedir RYKHTIK
 
Client Side MVC with Backbone and Rails
Client Side MVC with Backbone and RailsClient Side MVC with Backbone and Rails
Client Side MVC with Backbone and RailsTom Z Zeng
 
[aOS N°2] DevOps & SharePoint - Michel Hubert
[aOS N°2] DevOps & SharePoint - Michel Hubert[aOS N°2] DevOps & SharePoint - Michel Hubert
[aOS N°2] DevOps & SharePoint - Michel HubertCellenza
 
"8 Steps To Effectively Build A SharePoint Site" for SPS NYC
"8 Steps To Effectively Build A SharePoint Site" for SPS NYC"8 Steps To Effectively Build A SharePoint Site" for SPS NYC
"8 Steps To Effectively Build A SharePoint Site" for SPS NYCDux Raymond Sy
 
The Future of Everything
The Future of EverythingThe Future of Everything
The Future of EverythingCharbel Zeaiter
 

Destaque (8)

TYPO3 as Mobile Application Management System
TYPO3 as Mobile Application Management SystemTYPO3 as Mobile Application Management System
TYPO3 as Mobile Application Management System
 
DevOps for TYPO3 Teams and Projects
DevOps for TYPO3 Teams and ProjectsDevOps for TYPO3 Teams and Projects
DevOps for TYPO3 Teams and Projects
 
Chuong 3 mang
Chuong 3 mangChuong 3 mang
Chuong 3 mang
 
Client Side MVC with Backbone and Rails
Client Side MVC with Backbone and RailsClient Side MVC with Backbone and Rails
Client Side MVC with Backbone and Rails
 
[aOS N°2] DevOps & SharePoint - Michel Hubert
[aOS N°2] DevOps & SharePoint - Michel Hubert[aOS N°2] DevOps & SharePoint - Michel Hubert
[aOS N°2] DevOps & SharePoint - Michel Hubert
 
"8 Steps To Effectively Build A SharePoint Site" for SPS NYC
"8 Steps To Effectively Build A SharePoint Site" for SPS NYC"8 Steps To Effectively Build A SharePoint Site" for SPS NYC
"8 Steps To Effectively Build A SharePoint Site" for SPS NYC
 
WinAutomation Features
WinAutomation FeaturesWinAutomation Features
WinAutomation Features
 
The Future of Everything
The Future of EverythingThe Future of Everything
The Future of Everything
 

Semelhante a Unlearning and Relearning jQuery - Client-side Performance Optimization

Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web TechnologiesPerttu Myry
 
jQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesjQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesMark Roden
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupalBlackCatWeb
 
jQuery From the Ground Up
jQuery From the Ground UpjQuery From the Ground Up
jQuery From the Ground UpKevin Griffin
 
Upstate CSCI 450 jQuery
Upstate CSCI 450 jQueryUpstate CSCI 450 jQuery
Upstate CSCI 450 jQueryDanWooster1
 
Document Object Model
Document Object ModelDocument Object Model
Document Object ModelMayur Mudgal
 
Web components are the future of the web - Take advantage of new web technolo...
Web components are the future of the web - Take advantage of new web technolo...Web components are the future of the web - Take advantage of new web technolo...
Web components are the future of the web - Take advantage of new web technolo...Marios Fakiolas
 
Intro to jQuery @ Startup Institute
Intro to jQuery @ Startup InstituteIntro to jQuery @ Startup Institute
Intro to jQuery @ Startup InstituteRafael Gonzaque
 
Web Development Introduction to jQuery
Web Development Introduction to jQueryWeb Development Introduction to jQuery
Web Development Introduction to jQueryLaurence Svekis ✔
 
Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)Artur Cistov
 
jQuery - Chapter 1 - Introduction
 jQuery - Chapter 1 - Introduction jQuery - Chapter 1 - Introduction
jQuery - Chapter 1 - IntroductionWebStackAcademy
 
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneJavascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneDeepu S Nath
 
Building high performance web apps.
Building high performance web apps.Building high performance web apps.
Building high performance web apps.Arshak Movsisyan
 
Front-end optimisation & jQuery Internals
Front-end optimisation & jQuery InternalsFront-end optimisation & jQuery Internals
Front-end optimisation & jQuery InternalsArtur Cistov
 

Semelhante a Unlearning and Relearning jQuery - Client-side Performance Optimization (20)

Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web Technologies
 
jQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesjQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPages
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
 
jQuery
jQueryjQuery
jQuery
 
jQuery From the Ground Up
jQuery From the Ground UpjQuery From the Ground Up
jQuery From the Ground Up
 
Upstate CSCI 450 jQuery
Upstate CSCI 450 jQueryUpstate CSCI 450 jQuery
Upstate CSCI 450 jQuery
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
J Query
J QueryJ Query
J Query
 
Web components are the future of the web - Take advantage of new web technolo...
Web components are the future of the web - Take advantage of new web technolo...Web components are the future of the web - Take advantage of new web technolo...
Web components are the future of the web - Take advantage of new web technolo...
 
Intro to jQuery @ Startup Institute
Intro to jQuery @ Startup InstituteIntro to jQuery @ Startup Institute
Intro to jQuery @ Startup Institute
 
Web Development Introduction to jQuery
Web Development Introduction to jQueryWeb Development Introduction to jQuery
Web Development Introduction to jQuery
 
Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)
 
jQuery - Chapter 1 - Introduction
 jQuery - Chapter 1 - Introduction jQuery - Chapter 1 - Introduction
jQuery - Chapter 1 - Introduction
 
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and BackboneJavascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
Javascript Frameworks Comparison - Angular, Knockout, Ember and Backbone
 
What is HTML 5?
What is HTML 5?What is HTML 5?
What is HTML 5?
 
Building high performance web apps.
Building high performance web apps.Building high performance web apps.
Building high performance web apps.
 
Front-end optimisation & jQuery Internals
Front-end optimisation & jQuery InternalsFront-end optimisation & jQuery Internals
Front-end optimisation & jQuery Internals
 
J query
J queryJ query
J query
 

Último

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 

Último (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 

Unlearning and Relearning jQuery - Client-side Performance Optimization

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