SlideShare a Scribd company logo
1 of 66
2
3
Building High-Performance Web
    Applications and Sites
    John Hrvatin, Lead Program Manager
    johnhrv@microsoft.com
4
Session Objective(s):
      How to make your site faster today
      Principles to remember when building sites

    Key Takeaways
      Suggestions help in ALL browsers
      No magic solutions
      Consider maintainability



5
“…We are like dwarfs on the shoulders of
      giants, so that we can see more than they,
      and things at a greater distance, not by
      virtue of any sharpness of sight on our part,
      or any physical distinction, but because we
      are carried high and raised up by their giant
      size.quot;

    - Bernard of Chartres 1124


6
IE8 CPU usage: Top 100 Sites

                                   Layout, Rende
                                   ring, Formattin
             16%                   g, …



                                   JScript & DOM
                      84%




7
IE8 CPU usage: Top AJAX Sites

                                Layout, Rende
                                ring, Formattin
                                g, …
          33%


                         67%
                                JScript & DOM




8
CSS Performance
    Optimizing Symbol Resolution
    JavaScript Coding Inefficiencies
    HTTP Performance




9
CSS Performance
     Optimizing Symbol Resolution
     JavaScript Coding Inefficiencies
     HTTP Performance




10
Minimize included styles
       Unused styles increase download size
       Browser must parse and match all selectors
         Failures are expensive!




11
Simplify selectors
       Complex element selectors are slow
       When possible:
          Use class- or ID-based selectors
          Make element selectors as simple as possible
          Use child instead of descendent selectors
          Do not mix RTL and LTR styles
       Minimizing included styles makes this easier




12
Simplify selectors

  table tr td ul li {color: green;}
  li#pass {color: green;}



  ul li {color: purple;}
  ul > li {color: purple;}
Don't use expressions
       Slow – evaluated frequently
       Not supported in IE8 Standards Mode!




14
Minimize Page Re-layouts
      Poor user experience as content moves
      Browser performs unnecessary work




15
16
Takeaways

      Minimize included styles
      Use less-complicated selectors
      Don’t use expressions
      Minimize page re-layouts

      Simplify!



17
CSS Performance
     Optimizing Symbol Resolution
     JavaScript Coding Inefficiencies
     HTTP Performance




18
Lookup chains
      Scope                  Prototype
        var name              obj.name


                                   DOM
         Global

                                 Prototype
       Intermediate
                                    …
            …         Cost

                                  Instance
          Local



19
Local variables
 function WorkOnLocalVariable()
 {
     localVariable = foo();
     return ( localVariable + 1 );
 }
Local variables: Declare them as local
 function WorkOnLocalVariable2()
 {
     var localVariable = foo();
     return ( localVariable + 1 );
 }
Implicit lookups
 function BuildUI()
 {
     var elm = document.getElementById('ui');

     // Clear existing contents
     elm.innerHTML = '';          7 innerHTML
                                   References
     // Generate UI
     elm.innerHTML += BuildTitle();
                    +=
     elm.innerHTML += BuildBody();
                    +=
     elm.innerHTML += BuildFooter();
                    +=
 }
Implicit lookups: Batch changes
 function BuildUI2()
 {
     var elm = document.getElementById('ui');

                                     1 innerHTML
     // Generate UI
                                      Reference
     var contents = BuildTitle()
                  + BuildBody()
                  + BuildFooter();

     // Replace existing contents with UI
     elm.innerHTML = contents;
 }
Multiple DOM lookups
 function CalculateSum()
 {
     // Retrieve   Values
                   document.body.all
     var lSide =   document.body.all.lSide.value;
                   document.body.all
     var rSide =   document.body.all.rSide.value;

     // Generate Result
     document.body.all.result.value = lSide
     document.body.all
                                    + rSide;
 }
Multiple DOM lookups: Cache references
 function CalculateSum2()
 {
     // Cache Element Collection
     var elms = document.body.all;

     // Retrieve   Values
                   elms
     var lSide =   elms.lSide.value;
                   elms
     var rSide =   elms.rSide.value;

     // Generate Result
     elms
     elms.result.value = lSide + rSide;
 }
Function lookups
 function IterateWorkOverCollection()
 {
     var length = myCollection.length;

     for(var i = 0; i < length; i++)
     {
       Work
        Work(myCollection[i]);
     }
 }
Function lookups: Cache pointers
 function IterateWorkOverCollection2()
 {
     var funcWork = Work;
     var funcWork = Work;
     var length = myCollection.length;

     for(var i = 0; i < length; i++)
     {
       funcWork
        funcWork(myCollection[i]);
     }
 }
Takeaways

      Watch for expensive name lookups
      Cache repeated lookups to local variables

      Optimize only when needed
      Consider maintainability




28
29
CSS Performance Considerations
     Optimizing Symbol Resolution
     JavaScript Coding Inefficiencies
     HTTP Performance




30
Parsing JSON
      With eval
         Requires new script execution context (slow)
         Less secure

      With custom library
         More secure, but even slower




31
Parsing JSON: Use the native methods
      Built-in JSON methods:
         JSON.parse()
         JSON.stringify()
         toJSON() on prototypes of Date, Number, String,
         and Boolean
      Native equivalent of the reference parser from
      http://wiki.ecmascript.org/doku.php?id=es3.1:json
      _support
      As safe as http://www.json.org/json_parser.js
      but faster

32
33
The switch statement
 switch(option)
 {
      case 1: …
      case 2: …
      case 3: …
      …
      case 1000: …
 }
The switch statement: Use a lookup table
 var lookup = {
       1: function(){…}
       2: function(){…}
       3: function(){…}
       …
       1000: function(){…}
 }

 try {
    lookup[option]();
   lookup [option]();
 } catch(e) {
   // Default operation
 }
Property access methods
 var property = foo();

 this.getProperty = function()
 {
   return property;
 }

 this.setProperty = function(value)
 {
   property = value;
 }
Property access methods: Use direct access
 this.property = foo();
Property access methods
      Instantiating DOM functions
         Problems: Costly (in CPU cycles)
         Consider: Caching function pointers,
         batching changes
         Why: Generic Script Interface




38
Minimize DOM interaction
      Scope                  Prototype
        var name                obj.name


                                    DOM
         Global

                                  Prototype
       Intermediate
                                     …
            …         Cost

                                   Instance
          Local



39
Minimize DOM interaction
      Scope                  Prototype
        var name                obj.name


                                    DOM
         Global

                                  Prototype
       Intermediate
                                     …
            …         Cost

                                   Instance
          Local



40
Minimize DOM interaction
                 Trident (MSHTML)

                        DOM




                  JScript Engine


41
Minimize DOM interaction
 function getElementsByClassName(className, node, tag) {
       …
       var elements = node.getElementsByTagName(tag);
       var elements = node.getElementsByTagName(tag);
       var pattern = new RegExp(quot;(^|s)quot; + className +
 quot;(s|$)quot;);
                                 elements.length
       for(var i = 0, j = 0; i < elements.length; i++) {
                              elements[i]
             if (pattern.test(elements[i].className)) {
                   classElements[j] = elements[i];
                     j++;
             }
       }
       return classElements;
 }
Minimize DOM interaction
 function getElementsByClassName(className, node, tag)
 {
       …
       var results = node.getElementsByTagName(tag);
       var elements = new Array(results.length);
       var elements = new Array(results.length);
       while (length--) elements[length] = results[length];
       while (length--) elements[length] = results[length];
       var pattern = new RegExp(quot;(^|s)quot; + className +
 quot;(s|$)quot;);
       for(var i = 0, j = 0; i < elements.length i++) {
                                 elements.length;
                              elements[i]
             if (pattern.test(elements[i].className)) {
                   classElements.push(results[i]);    j++;
   }
       } return classElements;
 }
Smart use of DOM Methods
      Smart use of DOM methods can minimize
      overall DOM interaction
        nextSibling() better than childNodes[i]
        querySelectorAll() better for element groups




44
Smart use of DOM methods
 function LoopChildren(elm)
 {
   var nodes = elm.childNodes;
   var length = nodes.length;

     for(var i = 0; i < length; i++)
     {
       var node = nodes[i];
                  nodes[i];
       …
     }
 }
Smart use of DOM methods
 function LoopChildren2(elm)
 {
   var node = elm.firstChild;

     while(node != null)
     {
       …
       node = node.nextSibling;
     }
 }
Use querySelectorAll for groups
 function doValidation2()
 {
    // Retrieve the required elements by using Selectors
    // Selects all form fields with 'required' classes
    var reqs = document.querySelectorAll
               document.querySelectorAll(quot;.requiredquot;);

     // Set the flag to false by default
     var missingRequiredField = false;

     // Validate that the form data is not empty
     for (var i = 0; i < reqs.length; i++) {
        if (reqs[i].value == quot;quot;)
          missingRequiredField = true;
     }
 }
Takeaways

      Use the native JSON object
      Turn large switch statements into lookups
      Avoid property access methods
      Minimize DOM interaction
      Use querySelectorAll for groups

      Optimize only when needed
      Consider maintainability
49
CSS Performance
     Optimizing Symbol Resolution
     JavaScript Coding Inefficiencies
     HTTP Performance




50
Typical visit
       Request from Server / Cache
          JavaScript
          CSS
          Images
          HTML
       In Browser
          Layout
          Execute Script
          Additional downloads




51
HTTP compression: Use it
                                                      Response
     Request
     GET / HTTP/1.1                                   HTTP/1.1 200 OK
     Accept: */*                                      Content-Length: 3479
     Accept-Language: en-us                           Expires: -1
     UA-CPU: x86                                      Date: Tue, 24 Apr 2007 21:30:46 GMT
                                                      Content-Type: text/html; charset=utf-8
     Accept-Encoding: gzip, deflate
     User-Agent: Mozilla/4.0 (compatible; MSIE 7.0)   Pragma: no-cache
     Host: www.live.com                               Content-Encoding: gzip




52
Scaled images
 <html>
   <head>
      <title>Test</title>
   </head>
   <body>
      …
      <!-- icon.gif dimensions: 500 x 400 -->
      <img src=quot;icon.gifquot; width=quot;50quot; height=quot;40quot; />
      …
   </body>
 </html>
Scaled images: Use sized copies
 <html>
   <head>
      <title>Test</title>
   </head>
   <body>
      …
      <!-- icon2.gif dimensions: 50 x 40 -->
      <img src=quot;icon2.gifquot; width=quot;50quot; height=quot;40quot; />
      …
   </body>
 </html>
File linking
  <html>
    <head>
       <title>Test</title>
       <script src=“1.js” … ></script>
       <script src= type=quot;text/javascriptquot;></script>
      <script src=“2.js” … ></script>
      <link href=“1.css” … ></link>
      <link href=“2.css” … ></link>
    </head>
    <body>
       …
    </body>
  </html>
File linking: link one CSS file and one JS file
 <html>
   <head>
      <title>Test</title>
      <script src=“1+2.js” … ></script>
      <script type=quot;text/javascriptquot;></script>
      <link href=“1+2.css” … ></link>

   </head>
   <body>
      …
   </body>
 </html>
Many images
 <html>
   <head>
      <title>Test</title>
   </head>
   <body>
      …
      <img src=quot;a.gifquot; />   Item 1
      <img src=quot;b.gifquot; />   Item 2
      …
   </body>
 </html>
Many images: Combine and mask (sprites)
 <head>
    <title>Test</title>
    <style type=quot;text/cssquot;>
        .a, .b { width: 10; height: 10 }
        .a, .b { background-image: quot;abc.gifquot; }
        .a { background-position: 0   0}
        .b { background-position: 0 -10 }
        .b { background-position: 0 -10 }
    </style>
 </head>
 <body>
    …
    <div class=quot;aquot;></div> Item 1
    <div class=quot;aquot;></div>
    <div class=quot;bquot;></div>
    <div class=quot;bquot;></div> Item 2
    …
 </body>
Repeat visits

       Conditional HTTP Requests
         Plain HTTP Request
           Pragma: no-cache
         Time Conditional
           If-modified-since: date,time
       Provide cacheable content
         Time Conditional
           Expires: date,time
           Max-age: #seconds


59
Repeat visits: Use conditional requests
 Request                            Response
GET /images/banner.jpg HTTP/1.1      HTTP/1.1 304 Not Modified
Host: www.microsoft.com              Content-Type: image/jpeg
If-Modified-Since:                   Last-Modified:
    Wed, 22 Feb 2006 04:15:54 GMT        Wed, 22 Feb 2006 04:15:54 GMT




60
Repeat visits: Provide cacheable content
 Request                          Response
GET /images/banner.jpg HTTP/1.1    HTTP/1.1 200 OK
Host: www.microsoft.com            Content-Type: image/jpeg
                                   Expires: Fri, 12 Jun 2009 02:50:50 GMT




  Request                         Response
GET /images/banner.jpg HTTP/1.1


                                             No Response:
                                             Request Serviced from
                                             cache


61
Script blocking
 <html>
   <head>
      <title>Test</title>
      <script src=“1+2.js” … ></script>
      <script type=quot;text/javascriptquot;></script>
   </head>
   <body>
      …
   </body>
 </html>
Script blocking
 <html>
   <head>
      <title>Test</title>
   </head>
   <body>
      …
      <script src=“1+2.js” … ></script>
   </body>
 </html>
Tools

      Fiddler
         Inspect network traffic
         www.fiddler2.com
      neXpert
         Fiddler plug-in to aid performance testing
         http://www.fiddler2.com/fiddler2/addons/neXper
         t.asp



64
Takeaways
      Reduce the number of requests
        Combine external scripts, styles, and images
        Use caching
      Reduce the size of requests
        Use HTTP compression
        Use conditional requests
      Avoid blocking factors
        Put script at end of HTML


65
Identify the performance bottleneck
        Network / Bandwidth – using Fiddler
        JavaScript – using Developer Tools
        Aggressive DOM access – using Developer Tools

     Reduce, Simplify, Re-factor
        Reduce the bytes sent between the client/server
        Simplify your code to avoid costly JavaScript and CSS
        constructs
        Cache DOM properties and function pointers



66
Build High-Performance Web Apps

More Related Content

What's hot

Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserHoward Lewis Ship
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby CoreHiroshi SHIBATA
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptMichael Girouard
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Webnickmbailey
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptLeonardo Borges
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 

What's hot (20)

Dartprogramming
DartprogrammingDartprogramming
Dartprogramming
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
Polyglot JVM
Polyglot JVMPolyglot JVM
Polyglot JVM
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby Core
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Web
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Dispatch in Clojure
Dispatch in ClojureDispatch in Clojure
Dispatch in Clojure
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 

Viewers also liked

Beyond_Human_Interaction - Sensor and Location Platform
Beyond_Human_Interaction - Sensor and Location PlatformBeyond_Human_Interaction - Sensor and Location Platform
Beyond_Human_Interaction - Sensor and Location PlatformMithun T. Dhar
 
Newspaper source quide
Newspaper source quideNewspaper source quide
Newspaper source quideformanlibrary
 
Taking_Your-Application_To_The_Next_Level - Windows 7
Taking_Your-Application_To_The_Next_Level - Windows 7Taking_Your-Application_To_The_Next_Level - Windows 7
Taking_Your-Application_To_The_Next_Level - Windows 7Mithun T. Dhar
 
SharePoint FireStarter - Session 1 - Keynote - Eric Swift
SharePoint FireStarter - Session 1 - Keynote - Eric SwiftSharePoint FireStarter - Session 1 - Keynote - Eric Swift
SharePoint FireStarter - Session 1 - Keynote - Eric SwiftMithun T. Dhar
 
Session6-SharePoint and Azure- steve fox-windows-and_azure_spfs
Session6-SharePoint and Azure- steve fox-windows-and_azure_spfsSession6-SharePoint and Azure- steve fox-windows-and_azure_spfs
Session6-SharePoint and Azure- steve fox-windows-and_azure_spfsMithun T. Dhar
 

Viewers also liked (7)

Beyond_Human_Interaction - Sensor and Location Platform
Beyond_Human_Interaction - Sensor and Location PlatformBeyond_Human_Interaction - Sensor and Location Platform
Beyond_Human_Interaction - Sensor and Location Platform
 
Cobb Social Media Presentation - June 1
Cobb Social Media Presentation - June 1Cobb Social Media Presentation - June 1
Cobb Social Media Presentation - June 1
 
Pe 2
Pe 2Pe 2
Pe 2
 
Newspaper source quide
Newspaper source quideNewspaper source quide
Newspaper source quide
 
Taking_Your-Application_To_The_Next_Level - Windows 7
Taking_Your-Application_To_The_Next_Level - Windows 7Taking_Your-Application_To_The_Next_Level - Windows 7
Taking_Your-Application_To_The_Next_Level - Windows 7
 
SharePoint FireStarter - Session 1 - Keynote - Eric Swift
SharePoint FireStarter - Session 1 - Keynote - Eric SwiftSharePoint FireStarter - Session 1 - Keynote - Eric Swift
SharePoint FireStarter - Session 1 - Keynote - Eric Swift
 
Session6-SharePoint and Azure- steve fox-windows-and_azure_spfs
Session6-SharePoint and Azure- steve fox-windows-and_azure_spfsSession6-SharePoint and Azure- steve fox-windows-and_azure_spfs
Session6-SharePoint and Azure- steve fox-windows-and_azure_spfs
 

Similar to Build High-Performance Web Apps

the next web now
the next web nowthe next web now
the next web nowzulin Gu
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsMark Rackley
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Jimmy Schementi
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1Paras Mendiratta
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS InternalEyal Vardi
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsMark Rackley
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongTechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongGrokking VN
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongVu Huy
 

Similar to Build High-Performance Web Apps (20)

the next web now
the next web nowthe next web now
the next web now
 
JS Essence
JS EssenceJS Essence
JS Essence
 
IOC + Javascript
IOC + JavascriptIOC + Javascript
IOC + Javascript
 
SPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentialsSPTechCon - Share point and jquery essentials
SPTechCon - Share point and jquery essentials
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
17javascript.ppt
17javascript.ppt17javascript.ppt
17javascript.ppt
 
17javascript.ppt
17javascript.ppt17javascript.ppt
17javascript.ppt
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongTechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen Luong
 

More from Mithun T. Dhar

Concur State of Business Travel 2016
Concur State of Business Travel 2016Concur State of Business Travel 2016
Concur State of Business Travel 2016Mithun T. Dhar
 
Seattle Technical Forum-Insights of Travel
Seattle Technical Forum-Insights of TravelSeattle Technical Forum-Insights of Travel
Seattle Technical Forum-Insights of TravelMithun T. Dhar
 
ProgrammableWeb-API Conf-SF 2014
ProgrammableWeb-API Conf-SF 2014ProgrammableWeb-API Conf-SF 2014
ProgrammableWeb-API Conf-SF 2014Mithun T. Dhar
 
Concur-Evernote Conference 2014
Concur-Evernote Conference 2014Concur-Evernote Conference 2014
Concur-Evernote Conference 2014Mithun T. Dhar
 
Concur-Silicon Valley Code Camp - Mithun Dhar
Concur-Silicon Valley Code Camp - Mithun DharConcur-Silicon Valley Code Camp - Mithun Dhar
Concur-Silicon Valley Code Camp - Mithun DharMithun T. Dhar
 
Concur by the numbers...
Concur by the numbers...Concur by the numbers...
Concur by the numbers...Mithun T. Dhar
 
Session 7 - Integrating share point with silverlight firestarter
Session 7 - Integrating share point with silverlight firestarterSession 7 - Integrating share point with silverlight firestarter
Session 7 - Integrating share point with silverlight firestarterMithun T. Dhar
 
Session 5-SharePoint with Office-Donovan Follette
Session 5-SharePoint with Office-Donovan FolletteSession 5-SharePoint with Office-Donovan Follette
Session 5-SharePoint with Office-Donovan FolletteMithun T. Dhar
 
Session4-Sharepoint Online-chrismayo
Session4-Sharepoint Online-chrismayoSession4-Sharepoint Online-chrismayo
Session4-Sharepoint Online-chrismayoMithun T. Dhar
 
Session 3 - Developer Tools-Sharepoint firestarter-paul yuknewicz
Session 3 - Developer Tools-Sharepoint firestarter-paul yuknewiczSession 3 - Developer Tools-Sharepoint firestarter-paul yuknewicz
Session 3 - Developer Tools-Sharepoint firestarter-paul yuknewiczMithun T. Dhar
 
SeattleUniv-IntroductionToCloudComputing-WinsowsAzure101
SeattleUniv-IntroductionToCloudComputing-WinsowsAzure101SeattleUniv-IntroductionToCloudComputing-WinsowsAzure101
SeattleUniv-IntroductionToCloudComputing-WinsowsAzure101Mithun T. Dhar
 
SharePoint 2010 developer overview (in Visual Studio 2010)
SharePoint 2010 developer overview (in Visual Studio 2010)SharePoint 2010 developer overview (in Visual Studio 2010)
SharePoint 2010 developer overview (in Visual Studio 2010)Mithun T. Dhar
 
Azure Deployment(Seattle)
Azure Deployment(Seattle)Azure Deployment(Seattle)
Azure Deployment(Seattle)Mithun T. Dhar
 
Introduction To Cloud Computing Winsows Azure101
Introduction To Cloud Computing Winsows Azure101Introduction To Cloud Computing Winsows Azure101
Introduction To Cloud Computing Winsows Azure101Mithun T. Dhar
 
Building_The_Next-Generation_UI - Multitouch and Ribbon
Building_The_Next-Generation_UI - Multitouch and RibbonBuilding_The_Next-Generation_UI - Multitouch and Ribbon
Building_The_Next-Generation_UI - Multitouch and RibbonMithun T. Dhar
 
7-SilverlightFireStarter-Toolkit and Controls - Marco Matos
7-SilverlightFireStarter-Toolkit and Controls - Marco Matos7-SilverlightFireStarter-Toolkit and Controls - Marco Matos
7-SilverlightFireStarter-Toolkit and Controls - Marco MatosMithun T. Dhar
 
4-Silverlight FireStarter-ExpressionBlend_AdamKinney
4-Silverlight FireStarter-ExpressionBlend_AdamKinney4-Silverlight FireStarter-ExpressionBlend_AdamKinney
4-Silverlight FireStarter-ExpressionBlend_AdamKinneyMithun T. Dhar
 
5-Silverlight3_FIRESTARTER_sketchflow-Janete Perez
5-Silverlight3_FIRESTARTER_sketchflow-Janete Perez5-Silverlight3_FIRESTARTER_sketchflow-Janete Perez
5-Silverlight3_FIRESTARTER_sketchflow-Janete PerezMithun T. Dhar
 
3-Silverlight FireStarter - TimHeuer-Top Features and Scenarios
3-Silverlight FireStarter - TimHeuer-Top Features and Scenarios3-Silverlight FireStarter - TimHeuer-Top Features and Scenarios
3-Silverlight FireStarter - TimHeuer-Top Features and ScenariosMithun T. Dhar
 

More from Mithun T. Dhar (20)

Concur State of Business Travel 2016
Concur State of Business Travel 2016Concur State of Business Travel 2016
Concur State of Business Travel 2016
 
Seattle Technical Forum-Insights of Travel
Seattle Technical Forum-Insights of TravelSeattle Technical Forum-Insights of Travel
Seattle Technical Forum-Insights of Travel
 
Concur-Ford Hackathon
Concur-Ford HackathonConcur-Ford Hackathon
Concur-Ford Hackathon
 
ProgrammableWeb-API Conf-SF 2014
ProgrammableWeb-API Conf-SF 2014ProgrammableWeb-API Conf-SF 2014
ProgrammableWeb-API Conf-SF 2014
 
Concur-Evernote Conference 2014
Concur-Evernote Conference 2014Concur-Evernote Conference 2014
Concur-Evernote Conference 2014
 
Concur-Silicon Valley Code Camp - Mithun Dhar
Concur-Silicon Valley Code Camp - Mithun DharConcur-Silicon Valley Code Camp - Mithun Dhar
Concur-Silicon Valley Code Camp - Mithun Dhar
 
Concur by the numbers...
Concur by the numbers...Concur by the numbers...
Concur by the numbers...
 
Session 7 - Integrating share point with silverlight firestarter
Session 7 - Integrating share point with silverlight firestarterSession 7 - Integrating share point with silverlight firestarter
Session 7 - Integrating share point with silverlight firestarter
 
Session 5-SharePoint with Office-Donovan Follette
Session 5-SharePoint with Office-Donovan FolletteSession 5-SharePoint with Office-Donovan Follette
Session 5-SharePoint with Office-Donovan Follette
 
Session4-Sharepoint Online-chrismayo
Session4-Sharepoint Online-chrismayoSession4-Sharepoint Online-chrismayo
Session4-Sharepoint Online-chrismayo
 
Session 3 - Developer Tools-Sharepoint firestarter-paul yuknewicz
Session 3 - Developer Tools-Sharepoint firestarter-paul yuknewiczSession 3 - Developer Tools-Sharepoint firestarter-paul yuknewicz
Session 3 - Developer Tools-Sharepoint firestarter-paul yuknewicz
 
SeattleUniv-IntroductionToCloudComputing-WinsowsAzure101
SeattleUniv-IntroductionToCloudComputing-WinsowsAzure101SeattleUniv-IntroductionToCloudComputing-WinsowsAzure101
SeattleUniv-IntroductionToCloudComputing-WinsowsAzure101
 
SharePoint 2010 developer overview (in Visual Studio 2010)
SharePoint 2010 developer overview (in Visual Studio 2010)SharePoint 2010 developer overview (in Visual Studio 2010)
SharePoint 2010 developer overview (in Visual Studio 2010)
 
Azure Deployment(Seattle)
Azure Deployment(Seattle)Azure Deployment(Seattle)
Azure Deployment(Seattle)
 
Introduction To Cloud Computing Winsows Azure101
Introduction To Cloud Computing Winsows Azure101Introduction To Cloud Computing Winsows Azure101
Introduction To Cloud Computing Winsows Azure101
 
Building_The_Next-Generation_UI - Multitouch and Ribbon
Building_The_Next-Generation_UI - Multitouch and RibbonBuilding_The_Next-Generation_UI - Multitouch and Ribbon
Building_The_Next-Generation_UI - Multitouch and Ribbon
 
7-SilverlightFireStarter-Toolkit and Controls - Marco Matos
7-SilverlightFireStarter-Toolkit and Controls - Marco Matos7-SilverlightFireStarter-Toolkit and Controls - Marco Matos
7-SilverlightFireStarter-Toolkit and Controls - Marco Matos
 
4-Silverlight FireStarter-ExpressionBlend_AdamKinney
4-Silverlight FireStarter-ExpressionBlend_AdamKinney4-Silverlight FireStarter-ExpressionBlend_AdamKinney
4-Silverlight FireStarter-ExpressionBlend_AdamKinney
 
5-Silverlight3_FIRESTARTER_sketchflow-Janete Perez
5-Silverlight3_FIRESTARTER_sketchflow-Janete Perez5-Silverlight3_FIRESTARTER_sketchflow-Janete Perez
5-Silverlight3_FIRESTARTER_sketchflow-Janete Perez
 
3-Silverlight FireStarter - TimHeuer-Top Features and Scenarios
3-Silverlight FireStarter - TimHeuer-Top Features and Scenarios3-Silverlight FireStarter - TimHeuer-Top Features and Scenarios
3-Silverlight FireStarter - TimHeuer-Top Features and Scenarios
 

Recently uploaded

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Recently uploaded (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

Build High-Performance Web Apps

  • 1.
  • 2. 2
  • 3. 3
  • 4. Building High-Performance Web Applications and Sites John Hrvatin, Lead Program Manager johnhrv@microsoft.com 4
  • 5. Session Objective(s): How to make your site faster today Principles to remember when building sites Key Takeaways Suggestions help in ALL browsers No magic solutions Consider maintainability 5
  • 6. “…We are like dwarfs on the shoulders of giants, so that we can see more than they, and things at a greater distance, not by virtue of any sharpness of sight on our part, or any physical distinction, but because we are carried high and raised up by their giant size.quot; - Bernard of Chartres 1124 6
  • 7. IE8 CPU usage: Top 100 Sites Layout, Rende ring, Formattin 16% g, … JScript & DOM 84% 7
  • 8. IE8 CPU usage: Top AJAX Sites Layout, Rende ring, Formattin g, … 33% 67% JScript & DOM 8
  • 9. CSS Performance Optimizing Symbol Resolution JavaScript Coding Inefficiencies HTTP Performance 9
  • 10. CSS Performance Optimizing Symbol Resolution JavaScript Coding Inefficiencies HTTP Performance 10
  • 11. Minimize included styles Unused styles increase download size Browser must parse and match all selectors Failures are expensive! 11
  • 12. Simplify selectors Complex element selectors are slow When possible: Use class- or ID-based selectors Make element selectors as simple as possible Use child instead of descendent selectors Do not mix RTL and LTR styles Minimizing included styles makes this easier 12
  • 13. Simplify selectors table tr td ul li {color: green;} li#pass {color: green;} ul li {color: purple;} ul > li {color: purple;}
  • 14. Don't use expressions Slow – evaluated frequently Not supported in IE8 Standards Mode! 14
  • 15. Minimize Page Re-layouts Poor user experience as content moves Browser performs unnecessary work 15
  • 16. 16
  • 17. Takeaways Minimize included styles Use less-complicated selectors Don’t use expressions Minimize page re-layouts Simplify! 17
  • 18. CSS Performance Optimizing Symbol Resolution JavaScript Coding Inefficiencies HTTP Performance 18
  • 19. Lookup chains Scope Prototype var name obj.name DOM Global Prototype Intermediate … … Cost Instance Local 19
  • 20. Local variables function WorkOnLocalVariable() { localVariable = foo(); return ( localVariable + 1 ); }
  • 21. Local variables: Declare them as local function WorkOnLocalVariable2() { var localVariable = foo(); return ( localVariable + 1 ); }
  • 22. Implicit lookups function BuildUI() { var elm = document.getElementById('ui'); // Clear existing contents elm.innerHTML = ''; 7 innerHTML References // Generate UI elm.innerHTML += BuildTitle(); += elm.innerHTML += BuildBody(); += elm.innerHTML += BuildFooter(); += }
  • 23. Implicit lookups: Batch changes function BuildUI2() { var elm = document.getElementById('ui'); 1 innerHTML // Generate UI Reference var contents = BuildTitle() + BuildBody() + BuildFooter(); // Replace existing contents with UI elm.innerHTML = contents; }
  • 24. Multiple DOM lookups function CalculateSum() { // Retrieve Values document.body.all var lSide = document.body.all.lSide.value; document.body.all var rSide = document.body.all.rSide.value; // Generate Result document.body.all.result.value = lSide document.body.all + rSide; }
  • 25. Multiple DOM lookups: Cache references function CalculateSum2() { // Cache Element Collection var elms = document.body.all; // Retrieve Values elms var lSide = elms.lSide.value; elms var rSide = elms.rSide.value; // Generate Result elms elms.result.value = lSide + rSide; }
  • 26. Function lookups function IterateWorkOverCollection() { var length = myCollection.length; for(var i = 0; i < length; i++) { Work Work(myCollection[i]); } }
  • 27. Function lookups: Cache pointers function IterateWorkOverCollection2() { var funcWork = Work; var funcWork = Work; var length = myCollection.length; for(var i = 0; i < length; i++) { funcWork funcWork(myCollection[i]); } }
  • 28. Takeaways Watch for expensive name lookups Cache repeated lookups to local variables Optimize only when needed Consider maintainability 28
  • 29. 29
  • 30. CSS Performance Considerations Optimizing Symbol Resolution JavaScript Coding Inefficiencies HTTP Performance 30
  • 31. Parsing JSON With eval Requires new script execution context (slow) Less secure With custom library More secure, but even slower 31
  • 32. Parsing JSON: Use the native methods Built-in JSON methods: JSON.parse() JSON.stringify() toJSON() on prototypes of Date, Number, String, and Boolean Native equivalent of the reference parser from http://wiki.ecmascript.org/doku.php?id=es3.1:json _support As safe as http://www.json.org/json_parser.js but faster 32
  • 33. 33
  • 34. The switch statement switch(option) { case 1: … case 2: … case 3: … … case 1000: … }
  • 35. The switch statement: Use a lookup table var lookup = { 1: function(){…} 2: function(){…} 3: function(){…} … 1000: function(){…} } try { lookup[option](); lookup [option](); } catch(e) { // Default operation }
  • 36. Property access methods var property = foo(); this.getProperty = function() { return property; } this.setProperty = function(value) { property = value; }
  • 37. Property access methods: Use direct access this.property = foo();
  • 38. Property access methods Instantiating DOM functions Problems: Costly (in CPU cycles) Consider: Caching function pointers, batching changes Why: Generic Script Interface 38
  • 39. Minimize DOM interaction Scope Prototype var name obj.name DOM Global Prototype Intermediate … … Cost Instance Local 39
  • 40. Minimize DOM interaction Scope Prototype var name obj.name DOM Global Prototype Intermediate … … Cost Instance Local 40
  • 41. Minimize DOM interaction Trident (MSHTML) DOM JScript Engine 41
  • 42. Minimize DOM interaction function getElementsByClassName(className, node, tag) { … var elements = node.getElementsByTagName(tag); var elements = node.getElementsByTagName(tag); var pattern = new RegExp(quot;(^|s)quot; + className + quot;(s|$)quot;); elements.length for(var i = 0, j = 0; i < elements.length; i++) { elements[i] if (pattern.test(elements[i].className)) { classElements[j] = elements[i]; j++; } } return classElements; }
  • 43. Minimize DOM interaction function getElementsByClassName(className, node, tag) { … var results = node.getElementsByTagName(tag); var elements = new Array(results.length); var elements = new Array(results.length); while (length--) elements[length] = results[length]; while (length--) elements[length] = results[length]; var pattern = new RegExp(quot;(^|s)quot; + className + quot;(s|$)quot;); for(var i = 0, j = 0; i < elements.length i++) { elements.length; elements[i] if (pattern.test(elements[i].className)) { classElements.push(results[i]); j++; } } return classElements; }
  • 44. Smart use of DOM Methods Smart use of DOM methods can minimize overall DOM interaction nextSibling() better than childNodes[i] querySelectorAll() better for element groups 44
  • 45. Smart use of DOM methods function LoopChildren(elm) { var nodes = elm.childNodes; var length = nodes.length; for(var i = 0; i < length; i++) { var node = nodes[i]; nodes[i]; … } }
  • 46. Smart use of DOM methods function LoopChildren2(elm) { var node = elm.firstChild; while(node != null) { … node = node.nextSibling; } }
  • 47. Use querySelectorAll for groups function doValidation2() { // Retrieve the required elements by using Selectors // Selects all form fields with 'required' classes var reqs = document.querySelectorAll document.querySelectorAll(quot;.requiredquot;); // Set the flag to false by default var missingRequiredField = false; // Validate that the form data is not empty for (var i = 0; i < reqs.length; i++) { if (reqs[i].value == quot;quot;) missingRequiredField = true; } }
  • 48. Takeaways Use the native JSON object Turn large switch statements into lookups Avoid property access methods Minimize DOM interaction Use querySelectorAll for groups Optimize only when needed Consider maintainability 49
  • 49. CSS Performance Optimizing Symbol Resolution JavaScript Coding Inefficiencies HTTP Performance 50
  • 50. Typical visit Request from Server / Cache JavaScript CSS Images HTML In Browser Layout Execute Script Additional downloads 51
  • 51. HTTP compression: Use it Response Request GET / HTTP/1.1 HTTP/1.1 200 OK Accept: */* Content-Length: 3479 Accept-Language: en-us Expires: -1 UA-CPU: x86 Date: Tue, 24 Apr 2007 21:30:46 GMT Content-Type: text/html; charset=utf-8 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 7.0) Pragma: no-cache Host: www.live.com Content-Encoding: gzip 52
  • 52. Scaled images <html> <head> <title>Test</title> </head> <body> … <!-- icon.gif dimensions: 500 x 400 --> <img src=quot;icon.gifquot; width=quot;50quot; height=quot;40quot; /> … </body> </html>
  • 53. Scaled images: Use sized copies <html> <head> <title>Test</title> </head> <body> … <!-- icon2.gif dimensions: 50 x 40 --> <img src=quot;icon2.gifquot; width=quot;50quot; height=quot;40quot; /> … </body> </html>
  • 54. File linking <html> <head> <title>Test</title> <script src=“1.js” … ></script> <script src= type=quot;text/javascriptquot;></script> <script src=“2.js” … ></script> <link href=“1.css” … ></link> <link href=“2.css” … ></link> </head> <body> … </body> </html>
  • 55. File linking: link one CSS file and one JS file <html> <head> <title>Test</title> <script src=“1+2.js” … ></script> <script type=quot;text/javascriptquot;></script> <link href=“1+2.css” … ></link> </head> <body> … </body> </html>
  • 56. Many images <html> <head> <title>Test</title> </head> <body> … <img src=quot;a.gifquot; /> Item 1 <img src=quot;b.gifquot; /> Item 2 … </body> </html>
  • 57. Many images: Combine and mask (sprites) <head> <title>Test</title> <style type=quot;text/cssquot;> .a, .b { width: 10; height: 10 } .a, .b { background-image: quot;abc.gifquot; } .a { background-position: 0 0} .b { background-position: 0 -10 } .b { background-position: 0 -10 } </style> </head> <body> … <div class=quot;aquot;></div> Item 1 <div class=quot;aquot;></div> <div class=quot;bquot;></div> <div class=quot;bquot;></div> Item 2 … </body>
  • 58. Repeat visits Conditional HTTP Requests Plain HTTP Request Pragma: no-cache Time Conditional If-modified-since: date,time Provide cacheable content Time Conditional Expires: date,time Max-age: #seconds 59
  • 59. Repeat visits: Use conditional requests Request Response GET /images/banner.jpg HTTP/1.1 HTTP/1.1 304 Not Modified Host: www.microsoft.com Content-Type: image/jpeg If-Modified-Since: Last-Modified: Wed, 22 Feb 2006 04:15:54 GMT Wed, 22 Feb 2006 04:15:54 GMT 60
  • 60. Repeat visits: Provide cacheable content Request Response GET /images/banner.jpg HTTP/1.1 HTTP/1.1 200 OK Host: www.microsoft.com Content-Type: image/jpeg Expires: Fri, 12 Jun 2009 02:50:50 GMT Request Response GET /images/banner.jpg HTTP/1.1 No Response: Request Serviced from cache 61
  • 61. Script blocking <html> <head> <title>Test</title> <script src=“1+2.js” … ></script> <script type=quot;text/javascriptquot;></script> </head> <body> … </body> </html>
  • 62. Script blocking <html> <head> <title>Test</title> </head> <body> … <script src=“1+2.js” … ></script> </body> </html>
  • 63. Tools Fiddler Inspect network traffic www.fiddler2.com neXpert Fiddler plug-in to aid performance testing http://www.fiddler2.com/fiddler2/addons/neXper t.asp 64
  • 64. Takeaways Reduce the number of requests Combine external scripts, styles, and images Use caching Reduce the size of requests Use HTTP compression Use conditional requests Avoid blocking factors Put script at end of HTML 65
  • 65. Identify the performance bottleneck Network / Bandwidth – using Fiddler JavaScript – using Developer Tools Aggressive DOM access – using Developer Tools Reduce, Simplify, Re-factor Reduce the bytes sent between the client/server Simplify your code to avoid costly JavaScript and CSS constructs Cache DOM properties and function pointers 66