Ajax Performance Tuning and Best Practice



Similar documents
Web Performance. Lab. Bases de Dados e Aplicações Web MIEIC, FEUP 2014/15. Sérgio Nunes

Front-End Performance Testing and Optimization

Website Performance: Kyle Simpson

1. Minimize HTTP Requests. 2. Put Stylesheets at the Top

Performance Report for: Report generated: Friday, April 24, 2015, 7:29 AM (via API)

Improving Magento Front-End Performance

Mobile Application Performance Report

Web Performance. Sergey Chernyshev. March '09 New York Web Standards Meetup. New York, NY. March 19 th, 2009

MASTERTAG DEVELOPER GUIDE

Intro to Web Programming. using PHP, HTTP, CSS, and Javascript Layton Smith CSE 4000

Demystifying cache. Kristian Lyngstøl Product Specialist Varnish Software AS

making drupal run fast

Drupal Performance Tuning

Performance Testing for Ajax Applications

Datasheet - Sitekit CMS Performance Tips

Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator

Portals and Hosted Files

Performance testing Web 2.0

Accelerating Wordpress for Pagerank and Profit

PLAYER DEVELOPER GUIDE

Speed Matters. Simple Ways to Make Your Web Site Faster. Flickr: Uploaded February 11, 2007 by hawridger

Setup The package simply needs to be installed and configured for the desired CDN s distribution server.

How To Make Your Website More Exciting With A Browser Cache

79 Tips and Tricks for Magento Performance Improvement. for Magento Performance Improvement

reference: HTTP: The Definitive Guide by David Gourley and Brian Totty (O Reilly, 2002)

Speed up your web site. Alan Seiden Consulting alanseiden.com

WordPress Optimization

AJAX and JSON Lessons Learned. Jim Riecken, Senior Software Engineer, Blackboard Inc.

Cache Configuration Reference

A BASELINE FOR WEB PERFORMANCE WITH PHANTOMJS

Rich-Internet Anwendungen auf Basis von ColdFusion und Ajax

jquery Tutorial for Beginners: Nothing But the Goods

Website Optimization Tips for Speed

An introduction to creating Web 2.0 applications in Rational Application Developer Version 8.0

Design Approaches of Web Application with Efficient Performance in JAVA

Building a Simple Mobile optimized Web App/Site Using the jquery Mobile Framework

A Tool for Evaluation and Optimization of Web Application Performance

Cross Site Scripting (XSS) and PHP Security. Anthony Ferrara NYPHP and OWASP Security Series June 30, 2011

E-commerce is also about

Going Beyond SAP ITS Mobile Apps to a Responsive Design Mobile Apps. JK (JayaKumar Pedapudi) Principal Consultant NTT DATA, Inc.

Developing ASP.NET MVC 4 Web Applications MOC 20486

Debugging JavaScript and CSS Using Firebug. Harman Goei CSCI 571 1/27/13

Low Cost, High Performance, Strong Security: Pick Any Three. Chris Palmer isec Partners

Introduction to Ingeniux Forms Builder. 90 minute Course CMSFB-V6 P

AUDIT REPORT EXAMPLE

IBM Digital Experience. Using Modern Web Development Tools and Technology with IBM Digital Experience

Improved Speed on Intelligent Web Sites

Cache All The Things

Evaluation and Optimization of Web Application Performance Under Varying Network Conditions

S AMPLE CHAPTER. Dean Alan Hume MANNING

Visualizing a Neo4j Graph Database with KeyLines

Mobile Web Applications. Gary Dubuque IT Research Architect Department of Revenue

Mobile development with Apache OFBiz. Ean Schuessler, Brainfood

Web Development CSE2WD Final Examination June (a) Which organisation is primarily responsible for HTML, CSS and DOM standards?

Framework as a master tool in modern web development

HtmlUnit: An Efficient Approach to Testing Web Applications

ecommercesoftwareone Advance User s Guide -

Visualizing an OrientDB Graph Database with KeyLines

Bazaarvoice for Magento

What about MongoDB? can req.body.input 0; var date = new Date(); do {curdate = new Date();} while(curdate-date<10000)

Create interactive web graphics out of your SAS or R datasets

Web Development 1 A4 Project Description Web Architecture

Example. Represent this as XML

Kentico Site Delivery Checklist v1.1

Overview. In the beginning. Issues with Client Side Scripting What is JavaScript? Syntax and the Document Object Model Moving forward with JavaScript

Novell Identity Manager

O Reilly Ebooks Your bookshelf on your devices!

It is highly recommended that you are familiar with HTML and JavaScript before attempting this tutorial.

Client-side Web Engineering From HTML to AJAX

Developing ASP.NET MVC 4 Web Applications

Drupal CMS for marketing sites

metaengine DataConnect For SharePoint 2007 Configuration Guide

Presentation tier performance optimization

Distance Examination using Ajax to Reduce Web Server Load and Student s Data Transfer

Web application Architecture

The purpose of jquery is to make it much easier to use JavaScript on your website.

S AMPLE CHAPTER. Dean Alan Hume MANNING

Course Name: Course in JSP Course Code: P5

Web Dashboard User Guide

HTTP Caching & Cache-Busting for Content Publishers

THE PROXY SERVER 1 1 PURPOSE 3 2 USAGE EXAMPLES 4 3 STARTING THE PROXY SERVER 5 4 READING THE LOG 6

Ajax Development with ASP.NET 2.0

Why Web Performance Matters Open Text Web Solutions Usergroup Anwendertagung Feb Tobias Dreyschultze Tobel Online Web Consultancy

INFORMATION TECHNOLOGY STANDARD

Mobile Website Design for Libraries

HTML Application Creation. Rich Loen CTO, InGenius June 26, 2007

The importance of Drupal Cache. Luis F. Ribeiro Ci&T Inc. 2013

The Devil is in the Details. How to Optimize Magento Hosting to Increase Online Sales

GUI and Web Programming

Rich User Interfaces for Web-Based Corporate Applications

CMSC434 TUTORIAL #3 HTML CSS JavaScript Jquery Ajax + Google AppEngine Mobile WebApp HTML5

sessionx Desarrollo de Aplicaciones en Red Web Applications History (1) Content History (2) History (3)

Spectrum Technology Platform

Oracle Hyperion Financial Management Developer and Customization Guide

Sitecore Dashboard User Guide

Web-JISIS Reference Manual

Load Testing Ajax Apps using head-less browser tools. NoVaTAIG April 13, 2011 Gopal Addada and Frank Hurley Cigital Inc.

Using Steelhead Appliances and Stingray Aptimizer to Accelerate Microsoft SharePoint WHITE PAPER

HOW TO CREATE THEME IN MAGENTO 2

Kentico CMS, 2011 Kentico Software. Contents. Mobile Development using Kentico CMS 6 2 Exploring the Mobile Environment 1

Transcription:

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

eparation 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"; } ----------------------------------------------------------------------------------------------------------------------------------------------- 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"; Bad Good

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/blueprinttemplates.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