High Performance Ajax Applications

             Siarhei Barysiuk
      s.barysiuk@sam-solutions.net
Our roadmap
Introduction: What will we cover today?

• How to speed up site loading time?
• How to speed up JavaScript performance?
• ...
Best Practices from Yahoo!

34 best practices divided into 7 categories.
 • Content
 • Server
 • Cookie
 • CSS
 • JavaScri...
Server
Server
1. Use a Content Delivery Network
2. Add an Expires or a Cache-Control Header
3. Gzip Components
4. Configure ETags
...
Server: Use a CDN
Performance Golden Rule. “80-90% of the end-user response time is spent
downloading all the components i...
Server: Add an Expires or a Cache-Control Header
Static content:
Implement quot;Never expirequot; policy by setting far fu...
Server: Add an Expires or a Cache-Control Header
A web server uses the Expires header in the HTTP response to tell the
cli...
Server: Add an Expires or a Cache-Control Header
Loading http://www.yahoo.com with




         an empty cache            ...
Server: Gzip Components



           Accept-Encoding: gzip, deflate



               Content-Encoding: gzip
Server: Gzip Components
Gzipping generally reduces the response size by about 70%.


              Apache 1.3             ...
Server: Configure ETags
              GET /i/yahoo.gif HTTP/1.1



              HTTP/1.1 200 OK
              Last-Modifie...
Server: Configure ETags
Not very good for cluster environment.

The end result is ETags generated by Apache and IIS for the...
Server: Use GET for AJAX Requests

POST through XMLHttpRequest is a two-step process:

  • Sending headers
  • Sending dat...
Questions?
Content
Content
1. Make Fewer HTTP Requests
2. Reduce DNS Lookups
3. Avoid Redirects
4. Make Ajax Cacheable
5. Post-load Component...
Content: Make fewer HTTP Requests
80% of the end-user response time is spent on the front-end.
Most of this time is tied u...
Content: Make fewer HTTP Requests
Very interesting statistics:




         40-60% of Yahoo!’s users have an empty cache e...
Content: Make Ajax Cacheable
               “asynchronous” != “instantaneous”

Do not need to request some parts each time...
Content: Post-load Components
You can take a closer look at your page and ask yourself: quot;What's absolutely
required in...
Content: Preload Components
You can take advantage of the time the browser is idle and request components
(like images, st...
Content: Reduce the Number of DOM Elements

complex page = more bytes for download = slower DOM access

High number of DOM...
Content: Reduce the Number of DOM Elements
Content: Split Components Across Domains
Splitting components allows you to maximize parallel downloads.
Make sure you're ...
Content: Split Components Across Domains
HTTP/1.1 spec suggests that browsers download two components in parallel
per host...
Content: Split Components Across Domains
What if we use additional aliases to increase parallel downloads in our pages?


...
Content: Minimize the Number of iframes
It's important to understand how iframes work so they can be used effectively.
Pro...
Content: Minimize the Number of iframes




                       Demo
Questions?
Cookie
Cookie
1. Reduce Cookie Size
2. Use Cookie-free Domains for Components
Cookie: Reduce Cookie Size
HTTP cookies are used for a variety of reasons such as authentication and
personalization.

   ...
Cookie: Reduce Cookie Size
                                                             2x




                   Response...
Cookie: Reduce Cookie Size
Analysis of Cookie Sizes across the Web




                              Total Cookie Sizes *(...
Cookie: Reduce Cookie Size
Conclusion:
 • Eliminate unnecessary cookies.
 • Keep cookie sizes as low as possible to minimi...
Cookie: Use Cookie-free Domains for Components
When the browser makes a request for a static image and sends cookies
toget...
Questions?
CSS
CSS
1. Put Stylesheets at the Top
2. Avoid CSS Expressions
3. Choose <link> over @import
4. Avoid Filters
CSS: Put Stylesheets at the Top
Moving stylesheets to the document HEAD makes pages appear to be loading
faster. This is b...
CSS: Avoid CSS Expressions
CSS expressions are a powerful (and dangerous) way to set CSS properties
dynamically.

    back...
CSS: Choose <link> over @import
One of the previous best practices states that CSS should be at the top in order
to allow ...
CSS: Avoid Filters

The IE-proprietary AlphaImageLoader filter aims to fix a problem with semi-
transparent true color PNGs ...
Questions?
JavaScript
JavaScript
1. Put Scripts at the Bottom
2. Make JavaScript and CSS External
3. Minify JavaScript and CSS
4. Remove Duplica...
JavaScript: Put Scripts at the Bottom
The problem caused by scripts is that they block parallel downloads.
The HTTP/1.1 sp...
JavaScript: Make JavaScript and CSS External
Should JavaScript and CSS be contained in external files, or inlined in the pa...
JavaScript: Minify JavaScript and CSS
Minification is the practice of removing unnecessary characters from code to
reduce i...
JavaScript: Minify JavaScript and CSS
Tools:
                                                                         Clie...
JavaScript: Remove Duplicate Scripts
It hurts performance to include the same JavaScript file twice in one page.

• Extra H...
JavaScript: Minimize DOM Access
Accessing DOM elements with JavaScript is slow so in order to have a more
responsive page:...
JavaScript: Develop Smart Event Handlers
Sometimes pages feel less responsive because of too many event handlers
attached ...
Questions?
... more JavaScript performance
JavaScript: Reduce the amount of symbolic lookups

                                                   var globalVar = 0;
 ...
JavaScript: Reduce the amount of symbolic lookups
    var Foo3 = function() {};
	   Foo3.prototype.bar = function() {retur...
JavaScript: Reduce the amount of symbolic lookups


        var foo = new Foo();
	   	
                                   ...
JavaScript: String concatenation

                                                      var i,s=[];
         var i,s=quot;...
Questions?
Images
Images
1. Optimize Images
2. Optimize CSS Sprites
3. Don't Scale Images in HTML
4. Make favicon.ico Small and Cacheable
Images: Optimize Images
Tools:

imagemagick
pngcrush
jpegtran
Images: Optimize CSS Sprites
What is CSS Sprite?

http://www.google.com/images/nav_logo3.png


http://images.apple.com/glo...
Images: Optimize CSS Sprites




                        Demo
Images: Don't Scale Images in HTML
Don't use a bigger image than you need just because you can set the width and
height in...
Images: Make favicon.ico Small and Cacheable
The favicon.ico is an image that stays in the root of your server.

Even if y...
Questions?
Tools
Tools: Firebug
Tools:YSlow?
Tools: Drosera (WebKit)
Questions?
High Performance Ajax Applications
High Performance Ajax Applications
Upcoming SlideShare
Loading in...5
×

High Performance Ajax Applications

3,749

Published on

Day 6 of 7-days "JavaScript and Rich User Interfaces" training for my colleagues. It covers ways how to speed up your application.

Published in: Technology
0 Comments
10 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,749
On Slideshare
0
From Embeds
0
Number of Embeds
34
Actions
Shares
0
Downloads
233
Comments
0
Likes
10
Embeds 0
No embeds

No notes for slide

High Performance Ajax Applications

  1. 1. High Performance Ajax Applications Siarhei Barysiuk s.barysiuk@sam-solutions.net
  2. 2. Our roadmap
  3. 3. Introduction: What will we cover today? • How to speed up site loading time? • How to speed up JavaScript performance? • Which tools use to do it?
  4. 4. Best Practices from Yahoo! 34 best practices divided into 7 categories. • Content • Server • Cookie • CSS • JavaScript • Images • Mobile
  5. 5. Server
  6. 6. Server 1. Use a Content Delivery Network 2. Add an Expires or a Cache-Control Header 3. Gzip Components 4. Configure ETags 5. Flush the Buffer Early 6. Use GET for AJAX Requests
  7. 7. Server: Use a CDN Performance Golden Rule. “80-90% of the end-user response time is spent downloading all the components in the page: images, stylesheets, scripts, Flash, etc.” 20% end-user response time improvement at Yahoo!
  8. 8. Server: Add an Expires or a Cache-Control Header Static content: Implement quot;Never expirequot; policy by setting far future Expires header. For dynamic components: Use an appropriate Cache-Control header to help the browser with conditional requests.
  9. 9. Server: Add an Expires or a Cache-Control Header A web server uses the Expires header in the HTTP response to tell the client how long a component can be cached. Expires: Thu, 15 Apr 2010 20:00:00 GMT If you use a far future Expires header you have to change the component's filename whenever the component changes. yahoo_2.0.6.js yahoo.js?ver=2.0.6
  10. 10. Server: Add an Expires or a Cache-Control Header Loading http://www.yahoo.com with an empty cache a full cache
  11. 11. Server: Gzip Components Accept-Encoding: gzip, deflate Content-Encoding: gzip
  12. 12. Server: Gzip Components Gzipping generally reduces the response size by about 70%. Apache 1.3 mod-gzip Apache 2.0 mod-deflate IIS ...
  13. 13. Server: Configure ETags GET /i/yahoo.gif HTTP/1.1 HTTP/1.1 200 OK Last-Modified: Tue, 12 Dec 2006 03:03:59 GMT ETag: quot;10c24bc-4ab-457e1c1fquot; Content-Length: 12195 GET /i/yahoo.gif HTTP/1.1 Host: us.yimg.com If-Modified-Since: Tue, 12 Dec 2006 03:03:59 GMT If-None-Match: quot;10c24bc-4ab-457e1c1fquot; HTTP/1.1 304 Not Modified
  14. 14. Server: Configure ETags Not very good for cluster environment. The end result is ETags generated by Apache and IIS for the exact same component won't match from one server to another.
  15. 15. Server: Use GET for AJAX Requests POST through XMLHttpRequest is a two-step process: • Sending headers • Sending data So it's best to use GET, which only takes one TCP packet to send (unless you have a lot of cookies). The maximum URL length in IE is 2K, so if you send more than 2K data you might not be able to use GET.
  16. 16. Questions?
  17. 17. Content
  18. 18. Content 1. Make Fewer HTTP Requests 2. Reduce DNS Lookups 3. Avoid Redirects 4. Make Ajax Cacheable 5. Post-load Components 6. Preload Components 7. Reduce the Number of DOM Elements 8. Split Components Across Domains 9. Minimize the Number of iframes 10. No 404s
  19. 19. Content: Make fewer HTTP Requests 80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. One way to reduce the number of components in the page is to simplify the page's design. Other techniques: • Combined files • CSS Sprites • Image maps • Inline Images
  20. 20. Content: Make fewer HTTP Requests Very interesting statistics: 40-60% of Yahoo!’s users have an empty cache experience and ~20% of all page views are done with an empty cache.
  21. 21. Content: Make Ajax Cacheable “asynchronous” != “instantaneous” Do not need to request some parts each time, for example region-city list. Use Expires and Cache-Control headers Use additional parameter e.g. timestamp.
  22. 22. Content: Post-load Components You can take a closer look at your page and ask yourself: quot;What's absolutely required in order to render the page initially?quot; The rest of the content and components can wait. JavaScript: • Separate out a core • Add other components as extensions • Load them on demand Good for loading hidden content and images.
  23. 23. Content: Preload Components You can take advantage of the time the browser is idle and request components (like images, styles and scripts) you'll need in the future. Several types of preloading: • Unconditional (google.com and sprites) • Conditional • Anticipated (redesign)
  24. 24. Content: Reduce the Number of DOM Elements complex page = more bytes for download = slower DOM access High number of DOM elements can be a symptom that there's something that should be improved with the markup of the page without necessarily removing content.
  25. 25. Content: Reduce the Number of DOM Elements
  26. 26. Content: Split Components Across Domains Splitting components allows you to maximize parallel downloads. Make sure you're using not more than 2-4 domains because of the DNS lookup penalty. example.com static1.example.com static2.example.com
  27. 27. Content: Split Components Across Domains HTTP/1.1 spec suggests that browsers download two components in parallel per hostname. Downloading 2 Downloading 4 components in components in parallel parallel
  28. 28. Content: Split Components Across Domains What if we use additional aliases to increase parallel downloads in our pages? Loading an Empty HTML Document with 20 images using Various Number of Aliases
  29. 29. Content: Minimize the Number of iframes It's important to understand how iframes work so they can be used effectively. Pros: • Helps with slow third-party content like badges and ads • Security sandbox • Download scripts in parallel Cons: • Costly even if blank • Blocks page onload • Non-semantic
  30. 30. Content: Minimize the Number of iframes Demo
  31. 31. Questions?
  32. 32. Cookie
  33. 33. Cookie 1. Reduce Cookie Size 2. Use Cookie-free Domains for Components
  34. 34. Cookie: Reduce Cookie Size HTTP cookies are used for a variety of reasons such as authentication and personalization. GET www.yahoo.com/index.php HTTP/1.1 HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Set-Cookie: C=abcde; path=/; domain=.yahoo.com GET / HTTP/1.1 Host: finance.yahoo.com User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; ... Cookie: C=abcde;
  35. 35. Cookie: Reduce Cookie Size 2x Response times for various cookie sizes
  36. 36. Cookie: Reduce Cookie Size Analysis of Cookie Sizes across the Web Total Cookie Sizes *(for home page)
  37. 37. Cookie: Reduce Cookie Size Conclusion: • Eliminate unnecessary cookies. • Keep cookie sizes as low as possible to minimize the impact on the user response time. • Be mindful of setting cookies at the appropriate domain level so other sub-domains are not affected. • Set an Expires date appropriately. An earlier Expires date or none removes the cookie sooner, improving the user response time.
  38. 38. Cookie: Use Cookie-free Domains for Components When the browser makes a request for a static image and sends cookies together with the request, the server doesn't have any use for those cookies. Create a subdomain and host all your static components there. static.example.com
  39. 39. Questions?
  40. 40. CSS
  41. 41. CSS 1. Put Stylesheets at the Top 2. Avoid CSS Expressions 3. Choose <link> over @import 4. Avoid Filters
  42. 42. CSS: Put Stylesheets at the Top Moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. The problem with putting stylesheets near the bottom of the document is that it prohibits progressive rendering in many browsers, including Internet Explorer. These browsers block rendering to avoid having to redraw elements of the page if their styles change.
  43. 43. CSS: Avoid CSS Expressions CSS expressions are a powerful (and dangerous) way to set CSS properties dynamically. background-color: expression( (new Date()).getHours()%2 ? quot;#B8D4FFquot; : quot;#F08A00quot; ); The problem with expressions is that they are evaluated more frequently than most people expect. Moving the mouse around the page can easily generate more than 10,000 evaluations.
  44. 44. CSS: Choose <link> over @import One of the previous best practices states that CSS should be at the top in order to allow for progressive rendering. In IE @import behaves the same as using <link> at the bottom of the page, so it's best not to use it.
  45. 45. CSS: Avoid Filters The IE-proprietary AlphaImageLoader filter aims to fix a problem with semi- transparent true color PNGs in IE versions < 7. The problems: • blocks rendering • freezes the browser while the image is being downloaded • increases memory consumption and is applied per element
  46. 46. Questions?
  47. 47. JavaScript
  48. 48. JavaScript 1. Put Scripts at the Bottom 2. Make JavaScript and CSS External 3. Minify JavaScript and CSS 4. Remove Duplicate Scripts 5. Minimize DOM Access 6. Develop Smart Event Handlers
  49. 49. JavaScript: Put Scripts at the Bottom The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. DEFER
  50. 50. JavaScript: Make JavaScript and CSS External Should JavaScript and CSS be contained in external files, or inlined in the page itself? Pages which reuse External: the same scrips and styles • Cached by the browser • Parallel download Inline: Yahoo!'s front page • Less HTTP responses
  51. 51. JavaScript: Minify JavaScript and CSS Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times. // is.js // (c) 2001 Douglas Crockford // 2001 June 3 // is // The -is- object is used to identify the browser. Every browser edition // identifies itself, but there is no standard way of doing it, and some of // the identification is deceptive. This is because the authors of web // browsers are liars. For example, Microsoft's IE browsers claim to be var is={ie:navigator.appName=='Microsoft Internet // Mozilla 4. Netscape 6 claims to be version 5. Explorer',java:navigator.javaEnabled(),ns:navigator.appName=='Net scape',ua:navigator.userAgent.toLowerCase(),version:parseFloat(na var is = { vigator.appVersion.substr(21))|| ie: navigator.appName == 'Microsoft Internet Explorer', parseFloat(navigator.appVersion),win:navigator.platform=='Win32'} java: navigator.javaEnabled(), is.mac=is.ua.indexOf('mac')>=0;if(is.ua.indexOf('opera')>=0) ns: navigator.appName == 'Netscape', {is.ie=is.ns=false;is.opera=true;} ua: navigator.userAgent.toLowerCase(), if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;} version: parseFloat(navigator.appVersion.substr(21)) || parseFloat(navigator.appVersion), win: navigator.platform == 'Win32' } is.mac = is.ua.indexOf('mac') >= 0; if (is.ua.indexOf('opera') >= 0) { is.ie = is.ns = false; is.opera = true; } if (is.ua.indexOf('gecko') >= 0) { is.ie = is.ns = false; is.gecko = true; }
  52. 52. JavaScript: Minify JavaScript and CSS Tools: Client Remove Remove white Rename local safe performance comments spaces variables impact Dan Edward’s negative packer (uses eval) YUI Compressor neutral JSMin neutral qooxdoo positive generator.py (string optimizer)
  53. 53. JavaScript: Remove Duplicate Scripts It hurts performance to include the same JavaScript file twice in one page. • Extra HTTP request in IE • Time to process duplicated scripts Sounds stupid? A review of the ten top U.S. web sites shows that two of them contain a duplicated script.
  54. 54. JavaScript: Minimize DOM Access Accessing DOM elements with JavaScript is slow so in order to have a more responsive page: • Cache references to accessed elements • Update nodes quot;offlinequot; and then add them to the tree • Avoid fixing layout with JavaScript
  55. 55. JavaScript: Develop Smart Event Handlers Sometimes pages feel less responsive because of too many event handlers attached to different elements of the DOM tree which are then executed too often. That's why using event delegation is a good approach. <div class=quot;containerquot; id=quot;containerquot;> <div class=quot;colorquot; style=quot;background-color:#000033quot;></div> <div class=quot;colorquot; style=quot;background-color:#000066quot;></div> <div class=quot;colorquot; style=quot;background-color:#000099quot;></div> <div class=quot;colorquot; style=quot;background-color:#0000FFquot;></div> var c = document.getElementById(quot;containerquot;) <div class=quot;colorquot; style=quot;background-color:#003300quot;></div> <div class=quot;colorquot; style=quot;background-color:#006600quot;></div> c.addEventListener(quot;clickquot;, function(e){ <div class=quot;colorquot; style=quot;background-color:#009900quot;></div> <div class=quot;colorquot; style=quot;background-color:#00FF00quot;></div> alert(e.target.style.backgroundColor) },false); <div class=quot;colorquot; style=quot;background-color:#330000quot;></div> <div class=quot;colorquot; style=quot;background-color:#660000quot;></div> <div class=quot;colorquot; style=quot;background-color:#990000quot;></div> <div class=quot;colorquot; style=quot;background-color:#FF0000quot;></div> <div class=quot;colorquot; style=quot;background-color:#333333quot;></div> <div class=quot;colorquot; style=quot;background-color:#666666quot;></div> <div class=quot;colorquot; style=quot;background-color:#999999quot;></div> <div class=quot;colorquot; style=quot;background-color:#FFFFFFquot;></div> </div>
  56. 56. Questions?
  57. 57. ... more JavaScript performance
  58. 58. JavaScript: Reduce the amount of symbolic lookups var globalVar = 0; now = new Date(); (function(){ var globalVar = 0; var i,l,localVar; (function(){ l = arr.length; var i=0; for(i-0;i<arr.length;i++) { localVar = globalVar; globalVar++; for(i=0;i<l;i++){ } localVar++; })(); } globalVar = localVar; })(); 100 000 iterations
  59. 59. JavaScript: Reduce the amount of symbolic lookups var Foo3 = function() {}; Foo3.prototype.bar = function() {return false}; var Foo = function() {}; Foo.prototype = new Foo3(); var Foo2 = { bar: function() { return false; } }
  60. 60. JavaScript: Reduce the amount of symbolic lookups var foo = new Foo(); for(var j=0;j<iterations;j++) { for(var i=0;i<iterations;i++) { Foo2.bar(); foo.bar(); } } 10 000 000 iterations
  61. 61. JavaScript: String concatenation var i,s=[]; var i,s=quot;quot;; for(i=0;i<10000;i++){ for(i=0;i<10000;i++){ s[i] = quot;xquot;; s+=quot;xquot;; } } s=s.join(quot;quot;); 100 000 iterations 3438 ms 157 ms
  62. 62. Questions?
  63. 63. Images
  64. 64. Images 1. Optimize Images 2. Optimize CSS Sprites 3. Don't Scale Images in HTML 4. Make favicon.ico Small and Cacheable
  65. 65. Images: Optimize Images Tools: imagemagick pngcrush jpegtran
  66. 66. Images: Optimize CSS Sprites What is CSS Sprite? http://www.google.com/images/nav_logo3.png http://images.apple.com/global/nav/images/globalnavbg.png
  67. 67. Images: Optimize CSS Sprites Demo
  68. 68. Images: Don't Scale Images in HTML Don't use a bigger image than you need just because you can set the width and height in HTML. If you need <img width=quot;100quot; height=quot;100quot; src=quot;mycat.jpgquot; alt=quot;My Catquot; /> then your image (mycat.jpg) should be 100x100px rather than a scaled down 500x500px image.
  69. 69. Images: Make favicon.ico Small and Cacheable The favicon.ico is an image that stays in the root of your server. Even if you don't care about it the browser will still request it, so it's better not to respond with a 404 Not Found. Also since it's on the same server, cookies are sent every time it's requested. IE: When you request extra components in the onload, the favicon will be downloaded before these extra components. How to improve: • Make it small (under 1K) • Set appropriate Expires header
  70. 70. Questions?
  71. 71. Tools
  72. 72. Tools: Firebug
  73. 73. Tools:YSlow?
  74. 74. Tools: Drosera (WebKit)
  75. 75. Questions?
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×