SlideShare ist ein Scribd-Unternehmen logo
1 von 69
Downloaden Sie, um offline zu lesen
CODE MASH 2011
 DEVELOPING HIGH
PERFORMANCE WEB
       APPS
      Timothy Fisher
       Compuware
     January 14, 2011
WHO AM I?

                              Timothy Fisher
                              Technical Consultant
                              CTO Office - Emerging Technologies




                                    @tfisher
                                    tim.fisher@compuware.com
                                    www.timothyfisher.com

Download this presentation at: http://www.slideshare.net/timothyf
AGENDA
• Why   Front-end Performance Matters
• Optimize   Page Load
• Responsive   Interfaces
• Loading   and Executing JavaScript
• Data Access
AGENDA

• DOM     Scripting
• Tools

• Performance    Monitoring
• Questions


An overview to spark thought and further investigation
TRAIL BLAZERS

• Steve   Souders

• Nicholas   Zakas

• Stoyan    Stefanov

• Patrick   Meenan

• Sergey    Chernyshev
Why Front-end
Performance matters
According to Yahoo:
“80% of end-user response time is
spent on the front-end”

According to Steve Souders (Google performance guru):
“80-90% of end-user response
time is spent on the front-end”
Developing High Performance Web Apps - CodeMash 2011
Ads
                                     CDN’s




   Services
          Syndicated Content


Integration is happening on the client-side
OPTIMIZING FRONT END


•   Majority of end user response time spent on front end

•   Easier to optimize front end

•   Time spent optimizing here will have greatest impact
OPTIMIZE PAGE LOAD
PAGE LOAD TIME
              IS IMPORTANT
Page load time is critical to the success of a web site/app
         Google: +500 ms → -20% traffic

         Yahoo: +400 ms → -5-9% full-page traffic

         Amazon: +100 ms → -1% sales

Small performance flucutations affect traffic and sales!!!
BEST PRACTICES
•   Reduce HTTP Requests
    •   reduce overhead of page load

    •   combine javascript and css into less number of files

    •   combine images into sprites




•   Use a Content Delivery Network (CDN)
    •   static content delivered by fast distributed network with low latency

    •   content delivered closer to “last mile”
BEST PRACTICES
•   Make Pages Cacheable
    •   add expires header to pages

    •   use on all static content

    •   reduces HTTP requests


•   Use GZIP Page Compression
    •   all modern browsers support GZIP compression

    •   60-80% savings on text-based content

    •   No code changes required!
BEST PRACTICES
•   Place Stylesheets at the Top
    •   browser needs style info first to avoid repaints/reflows later
                                                                         CSS

    •   keep stylesheets external

    •   use <link>, do not use @import


•   Place Scripts at the Bottom
    •   allow page content to be rendered first

    •   keep scripts external to allow caching
                                                                       JavaScript
BEST PRACTICES

•   Minify JavaScript and CSS
    •   save bandwidth / download time

    •   lots of tools to automate this for you




•   Post/pre Load Components
    •   consider how you are loading content and scripts
BEST PRACTICES
•   Maximize Paralell Downloads
•   Split components across domains

•   each browser limits paralell downloads per domain

•   enables browser to load more stuff in parallel


•   Optimize Images
    •   avoid high-res images unless it is intentional

    •   don’t let the browser scale your images

    •   combine into sprites
CSS SPRITES

•   One image contains
    multiple web images

•   CSS styles used to
    display correct web
    image, i.e. position,
    background-position
RESPONSIVE INTERFACES
A SINGLE BROWSER THREAD
SINGLE THREAD
                   IMPLICATIONS
• Single   UI Thread for both UI updates and JavaScript execution

  • only   one of these can happen at a time!

  • Reason: JavaScript   may cause UI updates...

    Page downloading and rendering
    must stop and wait for scripts to be
    downloaded and executed
“0.1 second is about the limit for having the user feel
 that a system is reacting instantaneoulsy”
   - Jakob Nielsen, Usability Expert


Translation: No single JavaScript should execute for
more than 100 mS to ensure a responsive UI.
No limit to how long this can run...
  function processData(items, processor, callback) {
      for (var i=0, len=items.length; i<len; i++) {
          processor(items[i]);
      }
      callback();
  }



Will run no more than 50 mS...
  funcion timedProcessData(items, processor, callback) {
      var todo = items.concat(); // clone items
      setTimeout(funcion() {
          var start = new Date();
          do {
              processor(todo.shift());
          } while (todo.length > 0 && (new Date() - start < 50));
          if (todo.length > 0) {
               setTimeout(arguments.callee, 25);
          }
          else {
              callback(items);
          }
      }, 25);
  }
WEB WORKERS

• Commonly     associated with HTML5

• Allow   for asynchronous JavaScript execution

• JS   runs in a seperate thread isolated from the DOM

• Does    not delay UI updates

• Data   can be passed to/from Web Workers
Calling a Web Worker
    var worker = new Worker("worker.js");
    // Watch for messages from the worker
    worker.onmessage = function(e){
       // The message from the client:
       e.data
    };

    worker.postMessage("start");




The Web Worker client (worker.js)
    onmessage = function(e){
       if ( e.data === "start" ) {
         // Do some computation
         done()
       }
    };
    function done(){
       // Send back the results to the parent page
       postMessage("done");
    }
LOADING & EXECUTING
     JAVASCRIPT
WHY JAVASCRIPT?

•   Poorly written JavaScript is the most common reason
    for slow client-side performance

    • Loading

    • Parsing

    • Execution
TYPICAL JAVASCRIPT
             PLACEMENT
<html>
    <head>
        <link href=”style.css” rel=”stylesheet” type=”text/css”/>

       <script src=”myscript.js” type=”text/javascript”></script>
       <script src=”myscript.js” type=”text/javascript”></script>

       <script>
           function hello_world() {
                alert(‘hello world’);
           }
           var complex_data = // some complex calculation //
       </script>
   </head>

    <body>
        ...
    </body>
</html>
BETTER JAVASCRIPT
           PLACEMENT
<html>
    <head>
        <link href=”style.css” rel=”stylesheet” type=”text/css”/>
    </head>

   <body>
       ...

        <script src=”myscript.js” type=”text/javascript”></script>
        <script src=”myscript.js” type=”text/javascript”></script>
        <script>
            function hello_world() {
               alert(‘hello world’);
           }
            var complex_data = // some complex calculation
        </script>
    </body>
</html>
COMBINE JAVASCRIPT FILES
•   Each script request requires HTTP performance overhead

•   Minimize overhead by combining scripts


                                                  file.js
             file1.js    file2.js   file3.js




                                            =>

                       Browser                   Browser
MINIFY JAVASCRIPT

• Removes     all unecessary space/comments from your JS files

• Replace   variables with short names

• Easy   to do at built-time with a tool

• Checkout YUI    Compressor, Closure Compiler...


 Avoid manual code-size optimization!
NON-BLOCKING LOADS

• AddJavaScript to a page in a way that does not block the
 browser thread

 ‣ Dynamic Script Elements
 ‣ Script Injection
DYNAMIC SCRIPT ELEMENTS


• JavaScript
          is downloaded and executed without blocking
 other page processes.

  var script = document.createElement(‘script’);
  script.type = “text/javascript”;
  script.src = “file1.js”;
  document.getElementsByTagName(“head”)[0].appendChild(script);
SCRIPT INJECTION
• Use Ajax to get script
• Can control when script is parsed/executed
• JavaScript must be served from same domain
    var xhr = XMLHttpRequest();
    xhr.open(“get”, “file.js”, true);
    xhr.onreadystatechange = function() {
       if (xhr.readyState == 4) {
         if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
           var script = document.createElement(“script”);
           script.type = “text/javascript”;
           script.text = xhr.responseText;
           document.body.appendChild(script);
         }
       }
    };
    xhr.send(null);
RECOMMENDED
       NONBLOCKING LOAD

• Include the code necessary to dynamically load the the rest
 of the JS required for page init

    <script type="text/javascript" src="loader.js"></script>
    <script type="text/javascript">
        loadScript("the-rest.js", function(){
            Application.init();
        });
    </script>




  Optionally include the loadScript function directly in the page
REAL WORLD USE

• This
     technique is used by many JavaScript libraries including
 YUI and Dojo.

   <script type="text/javascript"
    src="http://yui.yahooapis.com/combo?3.0.0/build/yui/yui-min.js"></script>



   YUI().use("dom", function(Y){
       Y.DOM.addClass(document.body, "loaded");
   });




   Dynamically loads the DOM utility and calls ‘loaded’ function
   when loading is complete.
OPEN SOURCE JS LOADERS

Lots of libraries available to help with the JS load problem:

         •   ControlJS

         •   LabJS

         •   RequireJS
CONTROLJS


• Progessive   Enhancement is core to ControlJS philosophy

• downloads    scripts asynchronously

• delays   script execution until aftr the page has rendered

• allows   scripts to be downloaded and not executed
CONTROLJS
                    Async JS Loading
        var cjsscript = document.createElement('script');
        cjsscript.src = "control.js";
        var cjssib = document.getElementsByTagName('script')[0];
        cjssib.parentNode.insertBefore(cjsscript, cjssib);




Replace these script includes:
<script type="text/javascript" src="main.js"></script>



with:
<script type="text/cjs" data-cjssrc="main.js"></script>
CONTROLJS

                          Delayed Execution

<script data-cjsexec=false type="text/cjs" data-cjssrc="jquery.min.js"></script>
<script data-cjsexec=false type="text/cjs" data-cjssrc="fg.menu.js"></script>




      Execute at a later time...
              examplesbtn.onclick = function() {
                 CJS.execScript("jquery.min.js");
                 CJS.execScript("fg.menu.js", createExamplesMenu);
              };
LABJS

                   Async JS Loading


<script src="LAB.js"></script>




Load these scripts asynchronously:
$LAB.script('mootools-1.3.js');



$LAB.script('mootools-1.3.js').wait()
    .script('mootools-dependent-script.js');
SUMMARY

• Browser    UI and JS share a single thread

• Code  execution blocks other browser processes such as UI
 painting

• Put   script tags at the bottom of page

• Load   as much JS dynamically as possible

• Minimize   and compress your JS
DATA ACCESS
ACCESSING DATA
How you store and access data can have a significant
impact on performance...

         JavaScript Scope Chain
SCOPE CHAIN

Bad (deeper scope chain referencing repeatedly)
function innerHTMLLoop() {
    document.getElementById('ctrl1').innerHTML += 'a';
    document.getElementById('ctrl1').innerHTML += 'b';
    document.getElementById('ctrl1').innerHTML += 'c';
}




Better (save globals to local variables)
function innerHTMLLoop2() {
    var el = document.getElementById('ctrl1');
    el.innerHTML += 'a';
    el.innerHTML += 'b';
    el.innerHTML += ‘c’;
}
DOM SCRIPTING
DOCUMENT OBJECT MODEL


 • Document Object Model (DOM) is a language
  independent API for working with HTML and XML


 • DOM  Scripting is expensive and a common cause of
  performance problems
DOM/JS ISOLATION

•   DOM and JavaScript implementations are independent
    of each other in all major browsers

•   This causes overhead performance costs as these two
    pieces of code must interface


            JavaScri
                                      DOM
               pt


      Minimize how many times you cross this bridge
BAD DOM SCRIPTING

Bad (we cross the bridge 1500 times!)
function innerHTMLLoop() {
    for (var count = 0; count < 1500; count++) {
        document.getElementById('here').innerHTML += 'a';
    }
}




Good (we cross the bridge 1 time)
function innerHTMLLoop2() {
    var content = '';
    for (var count = 0; count < 1500; count++) {
        content += 'a';
    }
    document.getElementById('here').innerHTML += content;
}
REPAINTS AND REFLOWS
  A reflow occurs whenever you change the
  geometry of an element that is displayed on the
  page.

  A repaint occurs whenever you change the
  content of an element that is displayed on the
  screen.

These are both expensive operations in terms of performance!
AVOIDING REPAINTS/REFLOWS
  This will potentially cause 3 repaints/reflows...
  var el = document.getElementById('mydiv');
  el.style.borderLeft = '1px';
  el.style.borderRight = '2px';
  el.style.padding = '5px';




  Better...    1 repaint/reflow
  var el = document.getElementById('mydiv');
  el.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px;';


  or...
  var el = document.getElementById('mydiv');
  el.className = 'active';
TOOLS
TOOLS ARE YOUR FRIEND
The right tools can help a developer identify and fix
performance problems related to client-side behaviour.

  Profiling
  Timing functions and operations during script
  execution

  Network Analysis
  Examine loading of images, stylesheets, and scripts
  and their effect on page load and rendering
FIREBUG
•Firefox plugin
•Debug JavaScript
•View page load waterfall:
PAGE SPEED
•Extension to Firebug from Google
•Provides tips for improving page performance
Y-SLOW

•Extension to Firebug from Yahoo
•tips for improving page performance
DYNATRACE AJAX EDITION

•extension for IE, coming soon for Firefox
•deeper client-side tracing than the firebug extensions
SPEED TRACER

•performance extension for Google Chrome
•similar features to Dynatrace Ajax
YUI PROFILER
•profile JavaScript performance
•developer must insert JS code
MORE TOOLS...

Internet Explorer Developer Tools

Safari Web Inspector

Chrome Developer Tools


Lots of developer tools to debug performance!
PERFOMANCE MONITORING
SHOWSLOW

 collects:
   YSlow
   PageSpeed
   Dyantrace

Integrate with
WebPageTest
to run tests.



                 http://www.showslow.com/
WEB PAGE TEST

Tests against
dedicated nodes.

Agent deployed
on test nodes.

Image capture




                     http://www.webpagetest.org/
BOOMERANG
                              <html>
                                <head>

JavaScript library for Real
                                  <script src="boomerang.js" type="text/javascript"></script>
                                  <script type="text/javascript">
                                       BOOMR.init({
User Monitoring (RUM)         
     
    beacon_url: "http://yoursite.com/path/to/beacon.php"
                                       });
                                      BOOMR.plugins.RT.startTimer("t_head");
                                   </script>

Released by Yahoo in               <title>page title</title>
                                   <meta http-equiv="Content-type" content="text/html; charset=utf-8">

2010                               <link rel="stylesheet" type="text/css" href="../boomerang-docs.css">
                                   <script type="text/javascript">
                                      BOOMR.plugins.RT.endTimer("t_head").startTimer("t_body");
                                    </script>
                                  </head>

Beacon metrics to a               <body>
                                    page body here

central server                      <script type="text/javascript">
                                      BOOMR.plugins.RT.endTimer("t_body");
                                  </script>
                                </body>
                              </html>



                    https://github.com/yahoo/boomerang
W3C WEB PERFORMANCE
New W3C Working Group focused on web performance.

First recommendations:
 Navigation Timing - how fast does the page load
 Resource Timing - how fast do page resources load
 User Timing - user defined custom timing events


                http://www.w3.org/2010/webperf/
DON’T WANT TO DO
ALL OF THIS YOURSELF???
End-to-end application performance monitoring
RESOURCES
•   Yahoo Exceptional Performance
    http://developer.yahoo.com/performance/

•   Google Web Performance
    http://code.google.com/speed

•   JavaScript: The Good Parts by Douglas Crockford

•   High Performance JavaScript by Nicholas Zakas

•   Even Faster Websites by Steve Souders

•   Steve Souders Site
    http://www.stevesouders.com

•   John Resig’s Blog
    http://www.ejohn.org
QUESTIONS

Weitere ähnliche Inhalte

Was ist angesagt?

Service workers your applications never felt so good
Service workers   your applications never felt so goodService workers   your applications never felt so good
Service workers your applications never felt so goodChris Love
 
jQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript TestingjQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript TestingVlad Filippov
 
Using Web Standards to create Interactive Data Visualizations for the Web
Using Web Standards to create Interactive Data Visualizations for the WebUsing Web Standards to create Interactive Data Visualizations for the Web
Using Web Standards to create Interactive Data Visualizations for the Webphilogb
 
High Performance Web - Full Stack Toronto
High Performance Web - Full Stack TorontoHigh Performance Web - Full Stack Toronto
High Performance Web - Full Stack TorontoMaximiliano Firtman
 
Disrupting the application eco system with progressive web applications
Disrupting the application eco system with progressive web applicationsDisrupting the application eco system with progressive web applications
Disrupting the application eco system with progressive web applicationsChris Love
 
Html5 Fit: Get Rid of Love Handles
Html5 Fit:  Get Rid of Love HandlesHtml5 Fit:  Get Rid of Love Handles
Html5 Fit: Get Rid of Love HandlesChris Love
 
Adobe AEM CQ5 - Developer Introduction
Adobe AEM CQ5 - Developer IntroductionAdobe AEM CQ5 - Developer Introduction
Adobe AEM CQ5 - Developer IntroductionYash Mody
 
There Are No “Buts” in Progressive Enhancement [Øredev 2015]
There Are No “Buts” in Progressive Enhancement [Øredev 2015]There Are No “Buts” in Progressive Enhancement [Øredev 2015]
There Are No “Buts” in Progressive Enhancement [Øredev 2015]Aaron Gustafson
 
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...David Kaneda
 
jQuery Conference Boston 2011 CouchApps
jQuery Conference Boston 2011 CouchAppsjQuery Conference Boston 2011 CouchApps
jQuery Conference Boston 2011 CouchAppsBradley Holt
 
10 things you can do to speed up your web app today 2016
10 things you can do to speed up your web app today 201610 things you can do to speed up your web app today 2016
10 things you can do to speed up your web app today 2016Chris Love
 
State of jQuery June 2013 - Portland
State of jQuery June 2013 - PortlandState of jQuery June 2013 - Portland
State of jQuery June 2013 - Portlanddmethvin
 
Going Fast on the Mobile Web
Going Fast on the Mobile WebGoing Fast on the Mobile Web
Going Fast on the Mobile WebJason Grigsby
 
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
 
Responsive Images and Performance
Responsive Images and PerformanceResponsive Images and Performance
Responsive Images and PerformanceMaximiliano Firtman
 
Optimizing Your WordPress Site: Why speed matters, and how to get there
Optimizing Your WordPress Site: Why speed matters, and how to get thereOptimizing Your WordPress Site: Why speed matters, and how to get there
Optimizing Your WordPress Site: Why speed matters, and how to get thereStephen Bell
 
Thats Not Flash?
Thats Not Flash?Thats Not Flash?
Thats Not Flash?Mike Wilcox
 
Rails Performance Tricks and Treats
Rails Performance Tricks and TreatsRails Performance Tricks and Treats
Rails Performance Tricks and TreatsMarshall Yount
 
Real World Progressive Web Apps (Building Flipkart Lite)
Real World Progressive Web Apps (Building Flipkart Lite)Real World Progressive Web Apps (Building Flipkart Lite)
Real World Progressive Web Apps (Building Flipkart Lite)Abhinav Rastogi
 

Was ist angesagt? (20)

Service workers your applications never felt so good
Service workers   your applications never felt so goodService workers   your applications never felt so good
Service workers your applications never felt so good
 
jQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript TestingjQuery Chicago 2014 - Next-generation JavaScript Testing
jQuery Chicago 2014 - Next-generation JavaScript Testing
 
Using Web Standards to create Interactive Data Visualizations for the Web
Using Web Standards to create Interactive Data Visualizations for the WebUsing Web Standards to create Interactive Data Visualizations for the Web
Using Web Standards to create Interactive Data Visualizations for the Web
 
High Performance Web - Full Stack Toronto
High Performance Web - Full Stack TorontoHigh Performance Web - Full Stack Toronto
High Performance Web - Full Stack Toronto
 
Disrupting the application eco system with progressive web applications
Disrupting the application eco system with progressive web applicationsDisrupting the application eco system with progressive web applications
Disrupting the application eco system with progressive web applications
 
Html5 Fit: Get Rid of Love Handles
Html5 Fit:  Get Rid of Love HandlesHtml5 Fit:  Get Rid of Love Handles
Html5 Fit: Get Rid of Love Handles
 
Mobile web performance dwx13
Mobile web performance dwx13Mobile web performance dwx13
Mobile web performance dwx13
 
Adobe AEM CQ5 - Developer Introduction
Adobe AEM CQ5 - Developer IntroductionAdobe AEM CQ5 - Developer Introduction
Adobe AEM CQ5 - Developer Introduction
 
There Are No “Buts” in Progressive Enhancement [Øredev 2015]
There Are No “Buts” in Progressive Enhancement [Øredev 2015]There Are No “Buts” in Progressive Enhancement [Øredev 2015]
There Are No “Buts” in Progressive Enhancement [Øredev 2015]
 
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...
How to Develop a Rich, Native-quality User Experience for Mobile Using Web St...
 
jQuery Conference Boston 2011 CouchApps
jQuery Conference Boston 2011 CouchAppsjQuery Conference Boston 2011 CouchApps
jQuery Conference Boston 2011 CouchApps
 
10 things you can do to speed up your web app today 2016
10 things you can do to speed up your web app today 201610 things you can do to speed up your web app today 2016
10 things you can do to speed up your web app today 2016
 
State of jQuery June 2013 - Portland
State of jQuery June 2013 - PortlandState of jQuery June 2013 - Portland
State of jQuery June 2013 - Portland
 
Going Fast on the Mobile Web
Going Fast on the Mobile WebGoing Fast on the Mobile Web
Going Fast on the Mobile Web
 
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
 
Responsive Images and Performance
Responsive Images and PerformanceResponsive Images and Performance
Responsive Images and Performance
 
Optimizing Your WordPress Site: Why speed matters, and how to get there
Optimizing Your WordPress Site: Why speed matters, and how to get thereOptimizing Your WordPress Site: Why speed matters, and how to get there
Optimizing Your WordPress Site: Why speed matters, and how to get there
 
Thats Not Flash?
Thats Not Flash?Thats Not Flash?
Thats Not Flash?
 
Rails Performance Tricks and Treats
Rails Performance Tricks and TreatsRails Performance Tricks and Treats
Rails Performance Tricks and Treats
 
Real World Progressive Web Apps (Building Flipkart Lite)
Real World Progressive Web Apps (Building Flipkart Lite)Real World Progressive Web Apps (Building Flipkart Lite)
Real World Progressive Web Apps (Building Flipkart Lite)
 

Ähnlich wie Developing High Performance Web Apps - CodeMash 2011

Developing High Performance Web Apps
Developing High Performance Web AppsDeveloping High Performance Web Apps
Developing High Performance Web AppsTimothy Fisher
 
Introduction to Jquery
Introduction to JqueryIntroduction to Jquery
Introduction to JqueryGurpreet singh
 
Building performance into the new yahoo homepage presentation
Building performance into the new yahoo  homepage presentationBuilding performance into the new yahoo  homepage presentation
Building performance into the new yahoo homepage presentationmasudakram
 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! HomepageNicholas Zakas
 
Advanced Web Technology.pptx
Advanced Web Technology.pptxAdvanced Web Technology.pptx
Advanced Web Technology.pptxssuser35fdf2
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScriptkoppenolski
 
Cvcc performance tuning
Cvcc performance tuningCvcc performance tuning
Cvcc performance tuningJohn McCaffrey
 
7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websitesoazabir
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Jeremy Likness
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
JavaScript Performance Patterns
JavaScript Performance PatternsJavaScript Performance Patterns
JavaScript Performance PatternsStoyan Stefanov
 
ASP .Net Core SPA Templates
ASP .Net Core SPA TemplatesASP .Net Core SPA Templates
ASP .Net Core SPA TemplatesEamonn Boyle
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!Nicholas Zakas
 
Progressive Web Apps and React
Progressive Web Apps and ReactProgressive Web Apps and React
Progressive Web Apps and ReactMike Melusky
 

Ähnlich wie Developing High Performance Web Apps - CodeMash 2011 (20)

Developing High Performance Web Apps
Developing High Performance Web AppsDeveloping High Performance Web Apps
Developing High Performance Web Apps
 
Javascript & Jquery
Javascript & JqueryJavascript & Jquery
Javascript & Jquery
 
Introduction to Jquery
Introduction to JqueryIntroduction to Jquery
Introduction to Jquery
 
Sanjeev ghai 12
Sanjeev ghai 12Sanjeev ghai 12
Sanjeev ghai 12
 
Presentation Tier optimizations
Presentation Tier optimizationsPresentation Tier optimizations
Presentation Tier optimizations
 
Building performance into the new yahoo homepage presentation
Building performance into the new yahoo  homepage presentationBuilding performance into the new yahoo  homepage presentation
Building performance into the new yahoo homepage presentation
 
Performance on the Yahoo! Homepage
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! Homepage
 
Advanced Web Technology.pptx
Advanced Web Technology.pptxAdvanced Web Technology.pptx
Advanced Web Technology.pptx
 
Salesforce Performance hacks - Client Side
Salesforce Performance hacks - Client SideSalesforce Performance hacks - Client Side
Salesforce Performance hacks - Client Side
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScript
 
Ui dev@naukri-2011
Ui dev@naukri-2011Ui dev@naukri-2011
Ui dev@naukri-2011
 
Cvcc performance tuning
Cvcc performance tuningCvcc performance tuning
Cvcc performance tuning
 
7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
JavaScript Performance Patterns
JavaScript Performance PatternsJavaScript Performance Patterns
JavaScript Performance Patterns
 
ASP .Net Core SPA Templates
ASP .Net Core SPA TemplatesASP .Net Core SPA Templates
ASP .Net Core SPA Templates
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
 
Progressive Web Apps and React
Progressive Web Apps and ReactProgressive Web Apps and React
Progressive Web Apps and React
 

Kürzlich hochgeladen

AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 

Kürzlich hochgeladen (20)

AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 

Developing High Performance Web Apps - CodeMash 2011

  • 1. CODE MASH 2011 DEVELOPING HIGH PERFORMANCE WEB APPS Timothy Fisher Compuware January 14, 2011
  • 2. WHO AM I? Timothy Fisher Technical Consultant CTO Office - Emerging Technologies @tfisher tim.fisher@compuware.com www.timothyfisher.com Download this presentation at: http://www.slideshare.net/timothyf
  • 3. AGENDA • Why Front-end Performance Matters • Optimize Page Load • Responsive Interfaces • Loading and Executing JavaScript • Data Access
  • 4. AGENDA • DOM Scripting • Tools • Performance Monitoring • Questions An overview to spark thought and further investigation
  • 5. TRAIL BLAZERS • Steve Souders • Nicholas Zakas • Stoyan Stefanov • Patrick Meenan • Sergey Chernyshev
  • 7. According to Yahoo: “80% of end-user response time is spent on the front-end” According to Steve Souders (Google performance guru): “80-90% of end-user response time is spent on the front-end”
  • 9. Ads CDN’s Services Syndicated Content Integration is happening on the client-side
  • 10. OPTIMIZING FRONT END • Majority of end user response time spent on front end • Easier to optimize front end • Time spent optimizing here will have greatest impact
  • 12. PAGE LOAD TIME IS IMPORTANT Page load time is critical to the success of a web site/app Google: +500 ms → -20% traffic Yahoo: +400 ms → -5-9% full-page traffic Amazon: +100 ms → -1% sales Small performance flucutations affect traffic and sales!!!
  • 13. BEST PRACTICES • Reduce HTTP Requests • reduce overhead of page load • combine javascript and css into less number of files • combine images into sprites • Use a Content Delivery Network (CDN) • static content delivered by fast distributed network with low latency • content delivered closer to “last mile”
  • 14. BEST PRACTICES • Make Pages Cacheable • add expires header to pages • use on all static content • reduces HTTP requests • Use GZIP Page Compression • all modern browsers support GZIP compression • 60-80% savings on text-based content • No code changes required!
  • 15. BEST PRACTICES • Place Stylesheets at the Top • browser needs style info first to avoid repaints/reflows later CSS • keep stylesheets external • use <link>, do not use @import • Place Scripts at the Bottom • allow page content to be rendered first • keep scripts external to allow caching JavaScript
  • 16. BEST PRACTICES • Minify JavaScript and CSS • save bandwidth / download time • lots of tools to automate this for you • Post/pre Load Components • consider how you are loading content and scripts
  • 17. BEST PRACTICES • Maximize Paralell Downloads • Split components across domains • each browser limits paralell downloads per domain • enables browser to load more stuff in parallel • Optimize Images • avoid high-res images unless it is intentional • don’t let the browser scale your images • combine into sprites
  • 18. CSS SPRITES • One image contains multiple web images • CSS styles used to display correct web image, i.e. position, background-position
  • 21. SINGLE THREAD IMPLICATIONS • Single UI Thread for both UI updates and JavaScript execution • only one of these can happen at a time! • Reason: JavaScript may cause UI updates... Page downloading and rendering must stop and wait for scripts to be downloaded and executed
  • 22. “0.1 second is about the limit for having the user feel that a system is reacting instantaneoulsy” - Jakob Nielsen, Usability Expert Translation: No single JavaScript should execute for more than 100 mS to ensure a responsive UI.
  • 23. No limit to how long this can run... function processData(items, processor, callback) { for (var i=0, len=items.length; i<len; i++) { processor(items[i]); } callback(); } Will run no more than 50 mS... funcion timedProcessData(items, processor, callback) { var todo = items.concat(); // clone items setTimeout(funcion() { var start = new Date(); do { processor(todo.shift()); } while (todo.length > 0 && (new Date() - start < 50)); if (todo.length > 0) { setTimeout(arguments.callee, 25); } else { callback(items); } }, 25); }
  • 24. WEB WORKERS • Commonly associated with HTML5 • Allow for asynchronous JavaScript execution • JS runs in a seperate thread isolated from the DOM • Does not delay UI updates • Data can be passed to/from Web Workers
  • 25. Calling a Web Worker var worker = new Worker("worker.js"); // Watch for messages from the worker worker.onmessage = function(e){ // The message from the client: e.data }; worker.postMessage("start"); The Web Worker client (worker.js) onmessage = function(e){ if ( e.data === "start" ) { // Do some computation done() } }; function done(){ // Send back the results to the parent page postMessage("done"); }
  • 26. LOADING & EXECUTING JAVASCRIPT
  • 27. WHY JAVASCRIPT? • Poorly written JavaScript is the most common reason for slow client-side performance • Loading • Parsing • Execution
  • 28. TYPICAL JAVASCRIPT PLACEMENT <html> <head> <link href=”style.css” rel=”stylesheet” type=”text/css”/> <script src=”myscript.js” type=”text/javascript”></script> <script src=”myscript.js” type=”text/javascript”></script> <script> function hello_world() { alert(‘hello world’); } var complex_data = // some complex calculation // </script> </head> <body> ... </body> </html>
  • 29. BETTER JAVASCRIPT PLACEMENT <html> <head> <link href=”style.css” rel=”stylesheet” type=”text/css”/> </head> <body> ... <script src=”myscript.js” type=”text/javascript”></script> <script src=”myscript.js” type=”text/javascript”></script> <script> function hello_world() { alert(‘hello world’); } var complex_data = // some complex calculation </script> </body> </html>
  • 30. COMBINE JAVASCRIPT FILES • Each script request requires HTTP performance overhead • Minimize overhead by combining scripts file.js file1.js file2.js file3.js => Browser Browser
  • 31. MINIFY JAVASCRIPT • Removes all unecessary space/comments from your JS files • Replace variables with short names • Easy to do at built-time with a tool • Checkout YUI Compressor, Closure Compiler... Avoid manual code-size optimization!
  • 32. NON-BLOCKING LOADS • AddJavaScript to a page in a way that does not block the browser thread ‣ Dynamic Script Elements ‣ Script Injection
  • 33. DYNAMIC SCRIPT ELEMENTS • JavaScript is downloaded and executed without blocking other page processes. var script = document.createElement(‘script’); script.type = “text/javascript”; script.src = “file1.js”; document.getElementsByTagName(“head”)[0].appendChild(script);
  • 34. SCRIPT INJECTION • Use Ajax to get script • Can control when script is parsed/executed • JavaScript must be served from same domain var xhr = XMLHttpRequest(); xhr.open(“get”, “file.js”, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { var script = document.createElement(“script”); script.type = “text/javascript”; script.text = xhr.responseText; document.body.appendChild(script); } } }; xhr.send(null);
  • 35. RECOMMENDED NONBLOCKING LOAD • Include the code necessary to dynamically load the the rest of the JS required for page init <script type="text/javascript" src="loader.js"></script> <script type="text/javascript"> loadScript("the-rest.js", function(){ Application.init(); }); </script> Optionally include the loadScript function directly in the page
  • 36. REAL WORLD USE • This technique is used by many JavaScript libraries including YUI and Dojo. <script type="text/javascript" src="http://yui.yahooapis.com/combo?3.0.0/build/yui/yui-min.js"></script> YUI().use("dom", function(Y){ Y.DOM.addClass(document.body, "loaded"); }); Dynamically loads the DOM utility and calls ‘loaded’ function when loading is complete.
  • 37. OPEN SOURCE JS LOADERS Lots of libraries available to help with the JS load problem: • ControlJS • LabJS • RequireJS
  • 38. CONTROLJS • Progessive Enhancement is core to ControlJS philosophy • downloads scripts asynchronously • delays script execution until aftr the page has rendered • allows scripts to be downloaded and not executed
  • 39. CONTROLJS Async JS Loading var cjsscript = document.createElement('script'); cjsscript.src = "control.js"; var cjssib = document.getElementsByTagName('script')[0]; cjssib.parentNode.insertBefore(cjsscript, cjssib); Replace these script includes: <script type="text/javascript" src="main.js"></script> with: <script type="text/cjs" data-cjssrc="main.js"></script>
  • 40. CONTROLJS Delayed Execution <script data-cjsexec=false type="text/cjs" data-cjssrc="jquery.min.js"></script> <script data-cjsexec=false type="text/cjs" data-cjssrc="fg.menu.js"></script> Execute at a later time... examplesbtn.onclick = function() { CJS.execScript("jquery.min.js"); CJS.execScript("fg.menu.js", createExamplesMenu); };
  • 41. LABJS Async JS Loading <script src="LAB.js"></script> Load these scripts asynchronously: $LAB.script('mootools-1.3.js'); $LAB.script('mootools-1.3.js').wait() .script('mootools-dependent-script.js');
  • 42. SUMMARY • Browser UI and JS share a single thread • Code execution blocks other browser processes such as UI painting • Put script tags at the bottom of page • Load as much JS dynamically as possible • Minimize and compress your JS
  • 44. ACCESSING DATA How you store and access data can have a significant impact on performance... JavaScript Scope Chain
  • 45. SCOPE CHAIN Bad (deeper scope chain referencing repeatedly) function innerHTMLLoop() { document.getElementById('ctrl1').innerHTML += 'a'; document.getElementById('ctrl1').innerHTML += 'b'; document.getElementById('ctrl1').innerHTML += 'c'; } Better (save globals to local variables) function innerHTMLLoop2() { var el = document.getElementById('ctrl1'); el.innerHTML += 'a'; el.innerHTML += 'b'; el.innerHTML += ‘c’; }
  • 47. DOCUMENT OBJECT MODEL • Document Object Model (DOM) is a language independent API for working with HTML and XML • DOM Scripting is expensive and a common cause of performance problems
  • 48. DOM/JS ISOLATION • DOM and JavaScript implementations are independent of each other in all major browsers • This causes overhead performance costs as these two pieces of code must interface JavaScri DOM pt Minimize how many times you cross this bridge
  • 49. BAD DOM SCRIPTING Bad (we cross the bridge 1500 times!) function innerHTMLLoop() { for (var count = 0; count < 1500; count++) { document.getElementById('here').innerHTML += 'a'; } } Good (we cross the bridge 1 time) function innerHTMLLoop2() { var content = ''; for (var count = 0; count < 1500; count++) { content += 'a'; } document.getElementById('here').innerHTML += content; }
  • 50. REPAINTS AND REFLOWS A reflow occurs whenever you change the geometry of an element that is displayed on the page. A repaint occurs whenever you change the content of an element that is displayed on the screen. These are both expensive operations in terms of performance!
  • 51. AVOIDING REPAINTS/REFLOWS This will potentially cause 3 repaints/reflows... var el = document.getElementById('mydiv'); el.style.borderLeft = '1px'; el.style.borderRight = '2px'; el.style.padding = '5px'; Better... 1 repaint/reflow var el = document.getElementById('mydiv'); el.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px;'; or... var el = document.getElementById('mydiv'); el.className = 'active';
  • 52. TOOLS
  • 53. TOOLS ARE YOUR FRIEND The right tools can help a developer identify and fix performance problems related to client-side behaviour. Profiling Timing functions and operations during script execution Network Analysis Examine loading of images, stylesheets, and scripts and their effect on page load and rendering
  • 55. PAGE SPEED •Extension to Firebug from Google •Provides tips for improving page performance
  • 56. Y-SLOW •Extension to Firebug from Yahoo •tips for improving page performance
  • 57. DYNATRACE AJAX EDITION •extension for IE, coming soon for Firefox •deeper client-side tracing than the firebug extensions
  • 58. SPEED TRACER •performance extension for Google Chrome •similar features to Dynatrace Ajax
  • 59. YUI PROFILER •profile JavaScript performance •developer must insert JS code
  • 60. MORE TOOLS... Internet Explorer Developer Tools Safari Web Inspector Chrome Developer Tools Lots of developer tools to debug performance!
  • 62. SHOWSLOW collects: YSlow PageSpeed Dyantrace Integrate with WebPageTest to run tests. http://www.showslow.com/
  • 63. WEB PAGE TEST Tests against dedicated nodes. Agent deployed on test nodes. Image capture http://www.webpagetest.org/
  • 64. BOOMERANG <html> <head> JavaScript library for Real <script src="boomerang.js" type="text/javascript"></script> <script type="text/javascript"> BOOMR.init({ User Monitoring (RUM) beacon_url: "http://yoursite.com/path/to/beacon.php" }); BOOMR.plugins.RT.startTimer("t_head"); </script> Released by Yahoo in <title>page title</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> 2010 <link rel="stylesheet" type="text/css" href="../boomerang-docs.css"> <script type="text/javascript"> BOOMR.plugins.RT.endTimer("t_head").startTimer("t_body"); </script> </head> Beacon metrics to a <body> page body here central server <script type="text/javascript"> BOOMR.plugins.RT.endTimer("t_body"); </script> </body> </html> https://github.com/yahoo/boomerang
  • 65. W3C WEB PERFORMANCE New W3C Working Group focused on web performance. First recommendations: Navigation Timing - how fast does the page load Resource Timing - how fast do page resources load User Timing - user defined custom timing events http://www.w3.org/2010/webperf/
  • 66. DON’T WANT TO DO ALL OF THIS YOURSELF???
  • 68. RESOURCES • Yahoo Exceptional Performance http://developer.yahoo.com/performance/ • Google Web Performance http://code.google.com/speed • JavaScript: The Good Parts by Douglas Crockford • High Performance JavaScript by Nicholas Zakas • Even Faster Websites by Steve Souders • Steve Souders Site http://www.stevesouders.com • John Resig’s Blog http://www.ejohn.org

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. Accessing a DOM element always comes at a price. \nIt is not the same as accessing any other local or global variable in JavaScript.\n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n