ajax performance tuning and best practices
DESCRIPTION
Ajax Performance Tuning and Best PracticesPerhaps the most primary motivation to develop Ajax application is to have better user experience hence how to achieve the optimized response time becomes an important aspect in Ajax performance optimization. In this session, we will focus on discussing the improvement of the network transfer time and the JavaScript processing time as the server response is already generally well understood. We will use an Ajax framework case study to show how an Ajax optimization process can be used to optimize the performance. During the optimization process, we will demonstrate how to measure the performance, how to determine the bottlenecks and how to resolve the problems by applying various best practice. Various tools like NetBeans, Firebug, and YSlow will be illustrated to show when to use what and how to use them. The list of Ajax Performance tuning tips on combining CSS and JavaScript resources, setting the correct headers, using minifed JavaScript, GZip contents, and Strategically placing of CSS links and JavaScript tags will be discussed in the session. Intermediate level Ajax and Enterprise developers can really benefit from this session. After the session, the audience will be able to: -apply Ajax Performance Optimization process-choose the right tool and use them-lleverage various best practice and performance tuning tips-improve their Ajax application response time ultimatelyPerhaps the most primary motivation to develop Ajax application is to have better user experience hence how to achieve the optimized response time becomes an important aspect in Ajax performance optimization. In this session, we will focus on discussing the improvement of the network transfer time and the JavaScript processing time as the server response is already generally well understood. We will use an Ajax framework case study to show how an Ajax optimization process can be used to optimize the performance. During the optimization process, we will demonstrate how to measure the performance, how to determine the bottlenecks and how to resolve the problems by applying various best practice. Various tools like NetBeans, Firebug, and YSlow will be illustrated to show when to use what and how to use them. The list of Ajax Performance tuning tips on combining CSS and JavaScript resources, setting the correct headers, using minifed JavaScript, GZip contents, and Strategically placing of CSS links and JavaScript tags will be discussed in the session. Intermediate level Ajax and Enterprise developers can really benefit from this session. After the session, the audience will be able to: -apply Ajax Performance Optimization process-choose the right tool and use them-lleverage various best practice and performance tuning tips-improve their Ajax application response time ultimatelyTRANSCRIPT
![Page 1: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/1.jpg)
Ajax Performance Tuning and Best Practice
Greg Murray Doris Chen Ph.D.Netflix Sun Microsystems, lnc.Senior UI Engineer Staff Engineer
![Page 2: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/2.jpg)
Agenda> Optimization Strategies and Process> General Coding Best Practices> Measuring Performance> Performance Optimization Recommendations> Frameworks and Case Study> Summary and Resources
![Page 3: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/3.jpg)
3
Optimization Strategies and Process
![Page 4: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/4.jpg)
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
![Page 5: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/5.jpg)
Development/Optimization Process
OK?
![Page 6: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/6.jpg)
6
General Coding Best Practices
![Page 7: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/7.jpg)
7
JavaScript Best Practices
> Provide a clean separation of content, CSS, and JavaScript
> De-reference unused objects> Think Asynchronous> Working with Objects
![Page 8: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/8.jpg)
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
![Page 9: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/9.jpg)
Inline or ExternalInline 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">
![Page 10: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/10.jpg)
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*/}
![Page 11: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/11.jpg)
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);
![Page 12: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/12.jpg)
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"; } -----------------------------------------------------------------------------------------------------------------------------------------------
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; ds.backgroundColor = "white"; }
GoodGood
BadBad
![Page 13: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/13.jpg)
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>"; };};
![Page 14: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/14.jpg)
Demo
![Page 15: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/15.jpg)
Measuring Performance
![Page 16: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/16.jpg)
Manual Timing Method
function myFunctionToTest() {var start = new Date().getTime();... // body of the functionvar totalTime = new Date().getTime() - start;}
![Page 17: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/17.jpg)
Tool: Firebug and YSlow
![Page 18: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/18.jpg)
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
![Page 19: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/19.jpg)
Demo
![Page 20: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/20.jpg)
Performance Optimization Recommendations
![Page 21: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/21.jpg)
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
![Page 22: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/22.jpg)
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
![Page 23: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/23.jpg)
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
![Page 24: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/24.jpg)
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
![Page 25: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/25.jpg)
minify inline scripts, too
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
![Page 26: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/26.jpg)
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
![Page 27: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/27.jpg)
Example: Defer Loading Resources<script>var deferredLibs = [ '/resources/jquery.js' , '/resources/base.js'];addLibraries(libs : deferredLibs, function(args) { // initialize components });</script>
![Page 28: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/28.jpg)
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); }}
![Page 29: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/29.jpg)
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
![Page 30: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/30.jpg)
How to Implement> May configure on the server conf file> Implement in a servlet or a serlvet filterlong 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);
![Page 31: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/31.jpg)
Configure Etags (server)> Etags: validate entities, unique identifier returned in
responseETag: "10c24bc-4ab-457e1c1f"
> Used in conditional GET requestsGET /i/yahoo.gif HTTP/1.1Host: us.yimg.comIf-Modified-Since: Tue, 12 Dec 2008 03:03:59 GMTIf-None-Match: "10c24bc-4ab-457e1c1f"HTTP/1.1 304 Not Modified
> If ETag doesn't match, can't send 304
![Page 32: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/32.jpg)
Etag ImplementationString etag = cr.getContentHash();// get the If-None-Match headerString 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);}
![Page 33: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/33.jpg)
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
![Page 34: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/34.jpg)
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);}
![Page 35: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/35.jpg)
Frameworks and Case Study
![Page 36: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/36.jpg)
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
![Page 37: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/37.jpg)
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
![Page 38: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/38.jpg)
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>
![Page 39: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/39.jpg)
Demo
![Page 40: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/40.jpg)
Summary and Resources
![Page 41: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/41.jpg)
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
![Page 42: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/42.jpg)
Resources> Best practices and Guidelines
https://blueprints.dev.java.net/bpcatalog/conventions/javascript-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/
![Page 43: Ajax Performance Tuning and Best Practices](https://reader035.vdocuments.net/reader035/viewer/2022062512/554a534db4c90531228b4c18/html5/thumbnails/43.jpg)
43
Greg Murray Doris Chen Ph.D.Netflix Sun Microsystems, lnc.Ajax Architect Staff Engineer