SlideShare une entreprise Scribd logo
1  sur  43
Télécharger pour lire hors ligne
Ajax Performance Tuning
  and Best Practice

Greg Murray Doris Chen Ph.D.
Netflix              Sun Microsystems, lnc.
Senior UI Engineer       Staff Engineer
Agenda
>   Optimization Strategies and Process
>   General Coding Best Practices
>   Measuring Performance
>   Performance Optimization Recommendations
>   Frameworks and Case Study
>   Summary and Resources
Optimization Strategies
and Process




                          3
Performance Challenges
>   Not much control over the deployment
    environment
       Load balancers, choice of application servers,
        server configuration
>   Browser incompatibilities
>   Large development teams
>   Complex projects dependencies
>   Application spans client and server
>   Hard to diagnose and debug


                                                         4
Development/Optimization Process




                      OK?
General Coding Best Practices




                                6
JavaScript Best Practices
>   Provide a clean separation of content, CSS, and
    JavaScript
>   De-reference unused objects
>   Think Asynchronous
>   Working with Objects




                                                      7
Separation of content, CSS, and JavaScript
 >   A rich web application user interface is made up of
        content (HTML/XHTML)
        styles (CSS)
        JavaScript
 >   Place CSS and JavaScript code in separate files
        Optimize the bandwidth usage by having CSS and
         JavaScript file loaded only once
 >   Variables to decide using external or inline
            multiple page views per user per session
            many of pages re-use the same scripts and stylesheets
Inline or External
 Inline JavaScript and CSS in front page, but dynamically
 download the external files after the page has finished loading
 <style>#Styles</style>
 <script type="text/javascript">
 // JavaScript logic
 <script>
 <body>The quick brown fox...</body>

 -------------------------------------------------------------------------------------
 For multiple views per user, and reusable scripts/css:
 <link rel="stylesheet" type="text/css"
   href="cart.css">
 <body>The quick brown fox...</body>
 <script type="text/javascript" src="cart.js">
De-reference unused objects
 //delete objects
 var foo='Delete Me'; //do something with foo
 delete foo;

 // detach listeners (IE / W3C difference)
 someElement.removeEventListener(type, fn,
 false); // W3C
 someElement.detachEvent(type,fn); // IE

 // remove DOM elements
 someElement.parentNode.removeChild(someElement);

 // page onunload
 window.onunload= function() { /*do something*/}


                                                    10
Think Asynchronous
>   Prevents browsers from halting execution of a
    code block that might take a long time
>   Semi-Asynchronous – Like an Ajax request
       Use a callback
>   use setTimeout() in conjunction with a callback
    function longProcess({ name : value}, callback) {
        // do what needs to be done
        callback.apply({});
    }

    setTimeout(function() {
        longProcess({ name : 'greg'}, function() {
        alert('all done');
           }
    }, 0);
Working with Objects (I)
var i;
for (i = 0; i < divs.length; i += 1) {
    divs[i].style.color = "black";
    divs[i].style.border = thickness + 'px solid blue';
    divs[i].style.backgroundColor = "white";
}
                                                                                                                              Bad
-----------------------------------------------------------------------------------------------------------------------------------------------
var      border = thickness + 'px solid blue';
var      nrDivs = divs.length;
var      ds, i;
for      (i = 0; i < nrDivs; i += 1) {
         ds = divs[i].style;
         ds.color = "black";
         ds.border = border;
                                                                                                                          Good
         ds.backgroundColor = "white";
}
Working with Objects (II)
String Concatenation
window.tablebuilder = function() {
    var _header, _rows = [];
    this.setHeader = function(_headers) {
        _header = "<tr><th>" +
_headers.join("</th><th>") + "</tr>";
    };
    this.addRow = function(_cells) {
        _rows.push("<tr><td>" +
_cells.join("</td><td>") + "</td></tr>");
    };
    this.toString = function() {
        return "<table>" + _header +
          "<tbody>" + _rows.join("") + "</tbody>" +
          "</table>";
    };
};
Demo
Measuring Performance
Manual Timing Method

function myFunctionToTest() {
var start = new Date().getTime();
... // body of the function
var totalTime = new Date().getTime() - start;
}
Tool: Firebug and YSlow
YSlow
>   Performance lint tool
       Analyzes and measures web page performance
           All components on the page, including components
            dynamically created by JavaScript
       Offers suggestion for improvement
>   Scores web pages for each rule
>   Firefox add-on integrated with Firebug
>   Open source license
>   http://developer.yahoo.com/yslow
Demo
Performance Optimization
Recommendations
Recommendations
>   Make fewer HTTP requests
>   Put stylesheets at the top
>   Move scripts to the bottom
>   Minify JS
>   Defer Loading Resources
>   Add an Expires header
>   Configure Etags
>   Gzip Resources
Make fewer HTTP requests (content)
>   Simply page design
>   CSS sprites (best for components)
       http://alistapart.com/articles/sprites




>   Combined scripts, combined stylesheets
>   combining six scripts into one eliminates five
    HTTP requests
>   Make JS and CSS external
Put stylesheets at the top (css)
 >   Want the browser to display whatever content it
     has as soon as possible
        Avoids flash of unstyled content or blank white
         screen
 >   CSS at the bottom:
        prohibits progressive rendering in many browsers,
         including Internet Explorer
        browsers block rendering to avoid having to redraw
         elements of the page if their styles change
 >   Solution: put stylesheets in document head
        allows the page to render progressively
Move scripts to the bottom (javascript)
>   Scripts block parallel downloads across all
    hostnames




>   Scripts block rendering of everything below them
    in the page
>   Script defer attribute is not a solution
       IE only, not supported in other browsers
Minify JavaScript (javascript, css)
>   Minification is the practice of :
       removing comments
       removing white space characters (space, newline,
        and tab)
       condensing variable names (optional)
>   Popular tools for minifying JavaScript code
       JSMin http://crockford.com/javascript/jsmin
       YUI Compressor: can also minify CSS
       Dean Edwards Packer
>   Minifying both external and inlined scripts and
    styles
       minifying will still reduce the size by 5% or more
        even after you gzip
        minify inline scripts, too
Defer Loading Resources
>   If you have a large library or set of libraries, you
    don't need to load everything when a page is
    loaded
>   Resources can be html, scripts, or css
       Use Ajax Request
       Add script/css links using DOM
Example: Defer Loading Resources
<script>
var deferredLibs = [ '/resources/jquery.js' ,
'/resources/base.js'];
addLibraries(libs : deferredLibs,
             function(args) {
                // initialize components
              });
</script>
Example: Defer Loading Resources (cont.)
function addLibraries( libs, callback) {
  for(var i=0; i < libs.length; i+=1) {
    var head =
document.getElementsByTagName("head")[0];
    var s = document.createElement("script");
    // add callback tracking logic
    s.src = libs[i];
    head.appendChild(s);
  }
}
Add an Expires header (server)
>   Expires response header tells the client how long
    a component can be cached
       Browsers use a cache to reduce the number and
        size of HTTP requests
       Avoids unnecessary subsequent HTTP requests
       Expires headers most often used with images, but
        should be used for scripts, stylesheets, and Flash
       For static components:set a far future Expires
        header
       For dynamic components: use an appropriate
        Cache-Control header to help the browser with
        conditional requests
How to Implement
>   May configure on the server conf file
>   Implement in a servlet or a serlvet filter
long maxAge = 1209600L;
SimpleDateFormat sdf =
 new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
long created = System.currentTimeMillis();
Date expiredate = new Date(created + (maxAge* 1000) );
sdf.setTimeZone (TimeZone.getTimeZone("GMT"));
String expires = sdf.format(expiredate);
--------------------------------------------------------
resp.setHeader("Expires", expires);
resp.setHeader("Cache-Control", "public,max-age=" +
maxAge);
Configure Etags (server)
>   Etags: validate entities, unique identifier returned in
    response
     ETag: "10c24bc-4ab-457e1c1f"

>   Used in conditional GET requests
     GET /i/yahoo.gif HTTP/1.1
     Host: us.yimg.com
     If-Modified-Since: Tue, 12 Dec 2008 03:03:59 GMT
     If-None-Match: "10c24bc-4ab-457e1c1f"
     HTTP/1.1 304 Not Modified

>   If ETag doesn't match, can't send 304
Etag Implementation
 String etag = cr.getContentHash();
 // get the If-None-Match header
 String ifNoneMatch = req.getHeader("If-None-Match");
 if (etag != null &&
     ifNoneMatch != null &&
     ifNoneMatch.equals(etag)) {

   resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

 }
 if (etag != null) {
   resp.setHeader("ETag", etag);
 }
Gzip components (server)
>   you can affect users' download times
           Gzip supported in more browsers
           Gzip generally reduces the response size by 70%
        >   Not just for html, gzip all scripts,
              stylesheets, XML, JSON but not images, PDF
              Content-Encoding: gzip
>   Gzip configuration
           HTTP request
            Accept-Encoding: gzip, deflate
           HTTP response
            Content-Encoding: gzip
How to Implement gzip?
boolean canGzip = false;
Enumeration<String> hnum = req.getHeaders("Accept -Encoding");
while (hnum.hasMoreElements()) {
    String acceptType = hnum.nextElement();
    if (acceptType != null && acceptType.indexOf("gzip") != -1) {
        canGzip = true;
        break;
    }
}
if (canGzip ) {
    resp.setHeader("Vary", "Accept-Encoding");
    resp.setHeader("Content-Encoding", "gzip");
    OutputStream out = resp.getOutputStream();
    OutputStream bis = // get gzip outputstream of content
    IOUtil.writeBinaryResource(bis, out);
}
Frameworks and Case Study
Protorabbit
>   A CSS based templating and Ajax optimization
    framework
       Browsers and JavaScript neutral
>   Out of the box uses the BluePrint CSS framework
       You can easily substitute for extend the underlying
        framework
>   Defined in JSON format
       HTML based template that has properties that can
        be substituted with strings or the contents of a file
       specify the underlying HTML template, cache time
        for the template, scripts, CSS links, properties
       may extend any number of other templates with the
        child properties inheriting from their ancestors
Protorabbit (cont.)
>   Protorabbit Engine will sets
       correct headers, combines CSS and JavaScript
        assets (if specified)
       gzips those resources as the page is rendered
       surrounding final pages are also cached and gzipped
        for as long as you specify in your template
       can defer loading of scripts, styles or page fragments
       Includes HttpClient that can fetch content from
        external sources
       Different templates may override the cache times of
        their parents or just inherit them
>   http://wiki.github.com/gmurray/protorabbit
How to get Started?
>   Include protorabit jar, and org.json.jar files in WEB-
    INF/lib directory
>   Include the servlet reference, servlet mapping,
    template references, other parameters in web.xml
>   Include the CSS template files (Blueprint CSS or
    Yahoo Grid template frameworks)
>   Include the a JSON template (templates.json)
  <context-param>
     <description> Template Definitions</description>
     <param-name>prt-templates</param-name>
     <param-value>/WEB-INF/templates.json,/resources/blueprint/blueprint-
templates.json
</param-value>
  </context-param>
Demo
Summary and Resources
Summary
>   Performance optimization is an iterative process :
       Starts with a good architecture and page design
       Understand the page processing
       Client coding best practices matters
>   Optimization should be measured
>   Use optimization recommendations, frameworks
    and solutions
Resources
>   Best practices and Guidelines
       https://blueprints.dev.java.net/bpcatalog/conventions/ja
        vascript-recommendations.html
       http://developer.yahoo.com/performance/rules.html
>   Tool
       http://developer.yahoo.com/yslow
>   Protorabbit
       http://wiki.github.com/gmurray/protorabbit
>   Other Sites
       http://stevesouders.com/
       http://javascript.crockford.com/
Greg Murray Doris Chen Ph.D.
Netflix          Sun Microsystems, lnc.
Ajax Architect   Staff Engineer




                                      43

Contenu connexe

Tendances

Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...BradNeuberg
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup PerformanceGreg Whalin
 
OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchAppsBradley Holt
 
Progressive downloads and rendering (Stoyan Stefanov)
Progressive downloads and rendering (Stoyan Stefanov)Progressive downloads and rendering (Stoyan Stefanov)
Progressive downloads and rendering (Stoyan Stefanov)Ontico
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
Varnish Cache and its usage in the real world!
Varnish Cache and its usage in the real world!Varnish Cache and its usage in the real world!
Varnish Cache and its usage in the real world!Ivan Chepurnyi
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Serverhendrikvb
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...mfrancis
 
How to Make AJAX Applications Scream on the Client
How to Make AJAX Applications Scream on the ClientHow to Make AJAX Applications Scream on the Client
How to Make AJAX Applications Scream on the Clientgoodfriday
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 
Resource registries plone conf 2014
Resource registries plone conf 2014Resource registries plone conf 2014
Resource registries plone conf 2014Ramon Navarro
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Top5 scalabilityissues withappendix
Top5 scalabilityissues withappendixTop5 scalabilityissues withappendix
Top5 scalabilityissues withappendixColdFusionConference
 
Even faster django
Even faster djangoEven faster django
Even faster djangoGage Tseng
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsSiarhei Barysiuk
 

Tendances (20)

Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
OSCON 2011 CouchApps
OSCON 2011 CouchAppsOSCON 2011 CouchApps
OSCON 2011 CouchApps
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
Progressive downloads and rendering (Stoyan Stefanov)
Progressive downloads and rendering (Stoyan Stefanov)Progressive downloads and rendering (Stoyan Stefanov)
Progressive downloads and rendering (Stoyan Stefanov)
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
YouDrup_in_Drupal
YouDrup_in_DrupalYouDrup_in_Drupal
YouDrup_in_Drupal
 
Varnish Cache and its usage in the real world!
Varnish Cache and its usage in the real world!Varnish Cache and its usage in the real world!
Varnish Cache and its usage in the real world!
 
Mojo – Simple REST Server
Mojo – Simple REST ServerMojo – Simple REST Server
Mojo – Simple REST Server
 
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
 
How to Make AJAX Applications Scream on the Client
How to Make AJAX Applications Scream on the ClientHow to Make AJAX Applications Scream on the Client
How to Make AJAX Applications Scream on the Client
 
Intro To Couch Db
Intro To Couch DbIntro To Couch Db
Intro To Couch Db
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Resource registries plone conf 2014
Resource registries plone conf 2014Resource registries plone conf 2014
Resource registries plone conf 2014
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Top5 scalabilityissues withappendix
Top5 scalabilityissues withappendixTop5 scalabilityissues withappendix
Top5 scalabilityissues withappendix
 
Even faster django
Even faster djangoEven faster django
Even faster django
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 

En vedette

Server Side Events
Server Side EventsServer Side Events
Server Side Eventsthepilif
 
A Re-Introduction to Third-Party Scripting
A Re-Introduction to Third-Party ScriptingA Re-Introduction to Third-Party Scripting
A Re-Introduction to Third-Party Scriptingbenvinegar
 
Behind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsBehind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsGuillermo Mansilla
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsBG Java EE Course
 

En vedette (7)

AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Server Side Events
Server Side EventsServer Side Events
Server Side Events
 
A Re-Introduction to Third-Party Scripting
A Re-Introduction to Third-Party ScriptingA Re-Introduction to Third-Party Scripting
A Re-Introduction to Third-Party Scripting
 
Behind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsBehind the scenes of Real-Time Notifications
Behind the scenes of Real-Time Notifications
 
Ajax
AjaxAjax
Ajax
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 

Similaire à Ajax Performance Tuning and Best Practices

Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english versionSabino Labarile
 
Java script Learn Easy
Java script Learn Easy Java script Learn Easy
Java script Learn Easy prince Loffar
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web PerformanceAdam Lu
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
JavaScript front end performance optimizations
JavaScript front end performance optimizationsJavaScript front end performance optimizations
JavaScript front end performance optimizationsChris Love
 
Client Side Optimization
Client Side OptimizationClient Side Optimization
Client Side OptimizationPatrick Huesler
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...tdc-globalcode
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Nuxt.JS Introdruction
Nuxt.JS IntrodructionNuxt.JS Introdruction
Nuxt.JS IntrodructionDavid Ličen
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula Sorin Chiprian
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources frameworkmarcplmer
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 

Similaire à Ajax Performance Tuning and Best Practices (20)

Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english version
 
Java script
Java scriptJava script
Java script
 
前端概述
前端概述前端概述
前端概述
 
Java script Learn Easy
Java script Learn Easy Java script Learn Easy
Java script Learn Easy
 
Web-Performance
Web-PerformanceWeb-Performance
Web-Performance
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
 
Enhance Web Performance
Enhance Web PerformanceEnhance Web Performance
Enhance Web Performance
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
JavaScript front end performance optimizations
JavaScript front end performance optimizationsJavaScript front end performance optimizations
JavaScript front end performance optimizations
 
Sanjeev ghai 12
Sanjeev ghai 12Sanjeev ghai 12
Sanjeev ghai 12
 
Client Side Optimization
Client Side OptimizationClient Side Optimization
Client Side Optimization
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Html5 & less css
Html5 & less cssHtml5 & less css
Html5 & less css
 
Webpack
Webpack Webpack
Webpack
 
Nuxt.JS Introdruction
Nuxt.JS IntrodructionNuxt.JS Introdruction
Nuxt.JS Introdruction
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources framework
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 

Plus de Doris Chen

Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Doris Chen
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work EverywhereDoris Chen
 
Angular mobile angular_u
Angular mobile angular_uAngular mobile angular_u
Angular mobile angular_uDoris Chen
 
Lastest Trends in Web Development
Lastest Trends in Web DevelopmentLastest Trends in Web Development
Lastest Trends in Web DevelopmentDoris Chen
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Doris Chen
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...Doris Chen
 
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterPractical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterDoris Chen
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Doris Chen
 
What Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsWhat Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsDoris Chen
 
Windows 8 Opportunity
Windows 8 OpportunityWindows 8 Opportunity
Windows 8 OpportunityDoris Chen
 
Wins8 appfoforweb fluent
Wins8 appfoforweb fluentWins8 appfoforweb fluent
Wins8 appfoforweb fluentDoris Chen
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Doris Chen
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsDoris Chen
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Doris Chen
 
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Doris Chen
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3Doris Chen
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Doris Chen
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It TodayDoris Chen
 
Dive Into HTML5
Dive Into HTML5Dive Into HTML5
Dive Into HTML5Doris Chen
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It TodayDoris Chen
 

Plus de Doris Chen (20)

Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016Practical tipsmakemobilefaster oscon2016
Practical tipsmakemobilefaster oscon2016
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work Everywhere
 
Angular mobile angular_u
Angular mobile angular_uAngular mobile angular_u
Angular mobile angular_u
 
Lastest Trends in Web Development
Lastest Trends in Web DevelopmentLastest Trends in Web Development
Lastest Trends in Web Development
 
Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!Angular or Backbone: Go Mobile!
Angular or Backbone: Go Mobile!
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
 
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps FasterPractical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
Practical Performance Tips and Tricks to Make Your HTML/JavaScript Apps Faster
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
 
What Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS AppsWhat Web Developers Need to Know to Develop Native HTML5/JS Apps
What Web Developers Need to Know to Develop Native HTML5/JS Apps
 
Windows 8 Opportunity
Windows 8 OpportunityWindows 8 Opportunity
Windows 8 Opportunity
 
Wins8 appfoforweb fluent
Wins8 appfoforweb fluentWins8 appfoforweb fluent
Wins8 appfoforweb fluent
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 Apps
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
 
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Windows 8 apps with JavaScript, HTML5 & CSS3
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
 
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
Building Beautiful and Interactive Metro apps with JavaScript, HTML5 & CSS3
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 
Dive Into HTML5
Dive Into HTML5Dive Into HTML5
Dive Into HTML5
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 

Ajax Performance Tuning and Best Practices

  • 1. Ajax Performance Tuning and Best Practice Greg Murray Doris Chen Ph.D. Netflix Sun Microsystems, lnc. Senior UI Engineer Staff Engineer
  • 2. Agenda > Optimization Strategies and Process > General Coding Best Practices > Measuring Performance > Performance Optimization Recommendations > Frameworks and Case Study > Summary and Resources
  • 4. Performance Challenges > Not much control over the deployment environment  Load balancers, choice of application servers, server configuration > Browser incompatibilities > Large development teams > Complex projects dependencies > Application spans client and server > Hard to diagnose and debug 4
  • 6. General Coding Best Practices 6
  • 7. JavaScript Best Practices > Provide a clean separation of content, CSS, and JavaScript > De-reference unused objects > Think Asynchronous > Working with Objects 7
  • 8. Separation of content, CSS, and JavaScript > A rich web application user interface is made up of  content (HTML/XHTML)  styles (CSS)  JavaScript > Place CSS and JavaScript code in separate files  Optimize the bandwidth usage by having CSS and JavaScript file loaded only once > Variables to decide using external or inline  multiple page views per user per session  many of pages re-use the same scripts and stylesheets
  • 9. Inline or External Inline JavaScript and CSS in front page, but dynamically download the external files after the page has finished loading <style>#Styles</style> <script type="text/javascript"> // JavaScript logic <script> <body>The quick brown fox...</body> ------------------------------------------------------------------------------------- For multiple views per user, and reusable scripts/css: <link rel="stylesheet" type="text/css" href="cart.css"> <body>The quick brown fox...</body> <script type="text/javascript" src="cart.js">
  • 10. De-reference unused objects //delete objects var foo='Delete Me'; //do something with foo delete foo; // detach listeners (IE / W3C difference) someElement.removeEventListener(type, fn, false); // W3C someElement.detachEvent(type,fn); // IE // remove DOM elements someElement.parentNode.removeChild(someElement); // page onunload window.onunload= function() { /*do something*/} 10
  • 11. Think Asynchronous > Prevents browsers from halting execution of a code block that might take a long time > Semi-Asynchronous – Like an Ajax request  Use a callback > use setTimeout() in conjunction with a callback function longProcess({ name : value}, callback) { // do what needs to be done callback.apply({}); } setTimeout(function() { longProcess({ name : 'greg'}, function() { alert('all done'); } }, 0);
  • 12. Working with Objects (I) var i; for (i = 0; i < divs.length; i += 1) { divs[i].style.color = "black"; divs[i].style.border = thickness + 'px solid blue'; divs[i].style.backgroundColor = "white"; } Bad ----------------------------------------------------------------------------------------------------------------------------------------------- var border = thickness + 'px solid blue'; var nrDivs = divs.length; var ds, i; for (i = 0; i < nrDivs; i += 1) { ds = divs[i].style; ds.color = "black"; ds.border = border; Good ds.backgroundColor = "white"; }
  • 13. Working with Objects (II) String Concatenation window.tablebuilder = function() { var _header, _rows = []; this.setHeader = function(_headers) { _header = "<tr><th>" + _headers.join("</th><th>") + "</tr>"; }; this.addRow = function(_cells) { _rows.push("<tr><td>" + _cells.join("</td><td>") + "</td></tr>"); }; this.toString = function() { return "<table>" + _header + "<tbody>" + _rows.join("") + "</tbody>" + "</table>"; }; };
  • 14. Demo
  • 16. Manual Timing Method function myFunctionToTest() { var start = new Date().getTime(); ... // body of the function var totalTime = new Date().getTime() - start; }
  • 18. YSlow > Performance lint tool  Analyzes and measures web page performance  All components on the page, including components dynamically created by JavaScript  Offers suggestion for improvement > Scores web pages for each rule > Firefox add-on integrated with Firebug > Open source license > http://developer.yahoo.com/yslow
  • 19. Demo
  • 21. Recommendations > Make fewer HTTP requests > Put stylesheets at the top > Move scripts to the bottom > Minify JS > Defer Loading Resources > Add an Expires header > Configure Etags > Gzip Resources
  • 22. Make fewer HTTP requests (content) > Simply page design > CSS sprites (best for components)  http://alistapart.com/articles/sprites > Combined scripts, combined stylesheets > combining six scripts into one eliminates five HTTP requests > Make JS and CSS external
  • 23. Put stylesheets at the top (css) > Want the browser to display whatever content it has as soon as possible  Avoids flash of unstyled content or blank white screen > CSS at the bottom:  prohibits progressive rendering in many browsers, including Internet Explorer  browsers block rendering to avoid having to redraw elements of the page if their styles change > Solution: put stylesheets in document head  allows the page to render progressively
  • 24. Move scripts to the bottom (javascript) > Scripts block parallel downloads across all hostnames > Scripts block rendering of everything below them in the page > Script defer attribute is not a solution  IE only, not supported in other browsers
  • 25. Minify JavaScript (javascript, css) > Minification is the practice of :  removing comments  removing white space characters (space, newline, and tab)  condensing variable names (optional) > Popular tools for minifying JavaScript code  JSMin http://crockford.com/javascript/jsmin  YUI Compressor: can also minify CSS  Dean Edwards Packer > Minifying both external and inlined scripts and styles  minifying will still reduce the size by 5% or more even after you gzip minify inline scripts, too
  • 26. Defer Loading Resources > If you have a large library or set of libraries, you don't need to load everything when a page is loaded > Resources can be html, scripts, or css  Use Ajax Request  Add script/css links using DOM
  • 27. Example: Defer Loading Resources <script> var deferredLibs = [ '/resources/jquery.js' , '/resources/base.js']; addLibraries(libs : deferredLibs, function(args) { // initialize components }); </script>
  • 28. Example: Defer Loading Resources (cont.) function addLibraries( libs, callback) { for(var i=0; i < libs.length; i+=1) { var head = document.getElementsByTagName("head")[0]; var s = document.createElement("script"); // add callback tracking logic s.src = libs[i]; head.appendChild(s); } }
  • 29. Add an Expires header (server) > Expires response header tells the client how long a component can be cached  Browsers use a cache to reduce the number and size of HTTP requests  Avoids unnecessary subsequent HTTP requests  Expires headers most often used with images, but should be used for scripts, stylesheets, and Flash  For static components:set a far future Expires header  For dynamic components: use an appropriate Cache-Control header to help the browser with conditional requests
  • 30. How to Implement > May configure on the server conf file > Implement in a servlet or a serlvet filter long maxAge = 1209600L; SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); long created = System.currentTimeMillis(); Date expiredate = new Date(created + (maxAge* 1000) ); sdf.setTimeZone (TimeZone.getTimeZone("GMT")); String expires = sdf.format(expiredate); -------------------------------------------------------- resp.setHeader("Expires", expires); resp.setHeader("Cache-Control", "public,max-age=" + maxAge);
  • 31. Configure Etags (server) > Etags: validate entities, unique identifier returned in response ETag: "10c24bc-4ab-457e1c1f" > Used in conditional GET requests GET /i/yahoo.gif HTTP/1.1 Host: us.yimg.com If-Modified-Since: Tue, 12 Dec 2008 03:03:59 GMT If-None-Match: "10c24bc-4ab-457e1c1f" HTTP/1.1 304 Not Modified > If ETag doesn't match, can't send 304
  • 32. Etag Implementation String etag = cr.getContentHash(); // get the If-None-Match header String ifNoneMatch = req.getHeader("If-None-Match"); if (etag != null && ifNoneMatch != null && ifNoneMatch.equals(etag)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } if (etag != null) { resp.setHeader("ETag", etag); }
  • 33. Gzip components (server) > you can affect users' download times  Gzip supported in more browsers  Gzip generally reduces the response size by 70% > Not just for html, gzip all scripts, stylesheets, XML, JSON but not images, PDF Content-Encoding: gzip > Gzip configuration  HTTP request Accept-Encoding: gzip, deflate  HTTP response Content-Encoding: gzip
  • 34. How to Implement gzip? boolean canGzip = false; Enumeration<String> hnum = req.getHeaders("Accept -Encoding"); while (hnum.hasMoreElements()) { String acceptType = hnum.nextElement(); if (acceptType != null && acceptType.indexOf("gzip") != -1) { canGzip = true; break; } } if (canGzip ) { resp.setHeader("Vary", "Accept-Encoding"); resp.setHeader("Content-Encoding", "gzip"); OutputStream out = resp.getOutputStream(); OutputStream bis = // get gzip outputstream of content IOUtil.writeBinaryResource(bis, out); }
  • 36. Protorabbit > A CSS based templating and Ajax optimization framework  Browsers and JavaScript neutral > Out of the box uses the BluePrint CSS framework  You can easily substitute for extend the underlying framework > Defined in JSON format  HTML based template that has properties that can be substituted with strings or the contents of a file  specify the underlying HTML template, cache time for the template, scripts, CSS links, properties  may extend any number of other templates with the child properties inheriting from their ancestors
  • 37. Protorabbit (cont.) > Protorabbit Engine will sets  correct headers, combines CSS and JavaScript assets (if specified)  gzips those resources as the page is rendered  surrounding final pages are also cached and gzipped for as long as you specify in your template  can defer loading of scripts, styles or page fragments  Includes HttpClient that can fetch content from external sources  Different templates may override the cache times of their parents or just inherit them > http://wiki.github.com/gmurray/protorabbit
  • 38. How to get Started? > Include protorabit jar, and org.json.jar files in WEB- INF/lib directory > Include the servlet reference, servlet mapping, template references, other parameters in web.xml > Include the CSS template files (Blueprint CSS or Yahoo Grid template frameworks) > Include the a JSON template (templates.json) <context-param> <description> Template Definitions</description> <param-name>prt-templates</param-name> <param-value>/WEB-INF/templates.json,/resources/blueprint/blueprint- templates.json </param-value> </context-param>
  • 39. Demo
  • 41. Summary > Performance optimization is an iterative process :  Starts with a good architecture and page design  Understand the page processing  Client coding best practices matters > Optimization should be measured > Use optimization recommendations, frameworks and solutions
  • 42. Resources > Best practices and Guidelines  https://blueprints.dev.java.net/bpcatalog/conventions/ja vascript-recommendations.html  http://developer.yahoo.com/performance/rules.html > Tool  http://developer.yahoo.com/yslow > Protorabbit  http://wiki.github.com/gmurray/protorabbit > Other Sites  http://stevesouders.com/  http://javascript.crockford.com/
  • 43. Greg Murray Doris Chen Ph.D. Netflix Sun Microsystems, lnc. Ajax Architect Staff Engineer 43