SlideShare a Scribd company logo
1 of 77
Download to read offline
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?
• Which tools use to do it?
Best Practices from Yahoo!

34 best practices divided into 7 categories.
 • Content
 • Server
 • Cookie
 • CSS
 • JavaScript
 • Images
 • Mobile
Server
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
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!
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.
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
Server: Add an Expires or a Cache-Control Header
Loading http://www.yahoo.com with




         an empty cache                a full 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                mod-gzip

              Apache 2.0               mod-deflate

                  IIS

                  ...
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
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.
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.
Questions?
Content
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
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
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.
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.
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.
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)
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.
Content: Reduce the Number of DOM Elements
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
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
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
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
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.

                    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;
Cookie: Reduce Cookie Size
                                                             2x




                   Response times for various cookie sizes
Cookie: Reduce Cookie Size
Analysis of Cookie Sizes across the Web




                              Total Cookie Sizes *(for home page)
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.
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
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 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.
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.
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.
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
Questions?
JavaScript
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
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
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
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;
 }
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)
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.
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
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>
Questions?
... more JavaScript performance
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
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;
	   	}
	   }
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
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
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/global/nav/images/globalnavbg.png
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 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.
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
Questions?
Tools
Tools: Firebug
Tools:YSlow?
Tools: Drosera (WebKit)
Questions?

More Related Content

What's hot

Tuning Web Performance
Tuning Web PerformanceTuning Web Performance
Tuning Web PerformanceEric ShangKuan
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5dynamis
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?Remy Sharp
 
Front end performance optimization
Front end performance optimizationFront end performance optimization
Front end performance optimizationStevie T
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
Front end performance tip
Front end performance tipFront end performance tip
Front end performance tipSteve Yu
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkFabio Tiriticco
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSHannes Hapke
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksRandy Connolly
 
Internet Explorer 8 for Developers by Christian Thilmany
Internet Explorer 8 for Developers by Christian ThilmanyInternet Explorer 8 for Developers by Christian Thilmany
Internet Explorer 8 for Developers by Christian ThilmanyChristian Thilmany
 
Html5 drupal7 with mandakini kumari(1)
Html5 drupal7 with mandakini kumari(1)Html5 drupal7 with mandakini kumari(1)
Html5 drupal7 with mandakini kumari(1)Mandakini Kumari
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaJames Falkner
 
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)Clément Wehrung
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 

What's hot (20)

Tuning Web Performance
Tuning Web PerformanceTuning Web Performance
Tuning Web Performance
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?
 
Front end performance optimization
Front end performance optimizationFront end performance optimization
Front end performance optimization
 
Front End Performance
Front End PerformanceFront End Performance
Front End Performance
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Front end performance tip
Front end performance tipFront end performance tip
Front end performance tip
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Os Furlong
Os FurlongOs Furlong
Os Furlong
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
Internet Explorer 8 for Developers by Christian Thilmany
Internet Explorer 8 for Developers by Christian ThilmanyInternet Explorer 8 for Developers by Christian Thilmany
Internet Explorer 8 for Developers by Christian Thilmany
 
Html5 drupal7 with mandakini kumari(1)
Html5 drupal7 with mandakini kumari(1)Html5 drupal7 with mandakini kumari(1)
Html5 drupal7 with mandakini kumari(1)
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 

Similar to High Performance Ajax Applications

Frontend performance
Frontend performanceFrontend performance
Frontend performancesacred 8
 
High Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practicesHigh Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practicesStoyan Stefanov
 
The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...Otto Kekäläinen
 
Performace optimization (increase website speed)
Performace optimization (increase website speed)Performace optimization (increase website speed)
Performace optimization (increase website speed)clickramanm
 
A Holistic View of Website Performance
A Holistic View of Website PerformanceA Holistic View of Website Performance
A Holistic View of Website PerformanceRene Churchill
 
High performance website
High performance websiteHigh performance website
High performance websiteChamnap Chhorn
 
High Performance Websites
High Performance WebsitesHigh Performance Websites
High Performance WebsitesParham
 
Optimising Web Application Frontend
Optimising Web Application FrontendOptimising Web Application Frontend
Optimising Web Application Frontendtkramar
 
DrupalCampLA 2011 - Drupal frontend-optimizing
DrupalCampLA 2011 - Drupal frontend-optimizingDrupalCampLA 2011 - Drupal frontend-optimizing
DrupalCampLA 2011 - Drupal frontend-optimizingAshok Modi
 
7 Habits of Exceptional Performance
7 Habits of Exceptional Performance7 Habits of Exceptional Performance
7 Habits of Exceptional PerformanceNicole Sullivan
 
Heavy Web Optimization: Frontend
Heavy Web Optimization: FrontendHeavy Web Optimization: Frontend
Heavy Web Optimization: FrontendVõ Duy Tuấn
 
Website Performance
Website PerformanceWebsite Performance
Website PerformanceHugo Fonseca
 
The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013Bastian Grimm
 
Web Client Performance
Web Client PerformanceWeb Client Performance
Web Client PerformanceHerea Adrian
 
Csdn Drdobbs Tenni Theurer Yahoo
Csdn Drdobbs Tenni Theurer YahooCsdn Drdobbs Tenni Theurer Yahoo
Csdn Drdobbs Tenni Theurer Yahooguestb1b95b
 
SearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital Marketers
SearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital MarketersSearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital Marketers
SearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital MarketersDistilled
 

Similar to High Performance Ajax Applications (20)

Frontend performance
Frontend performanceFrontend performance
Frontend performance
 
Speed!
Speed!Speed!
Speed!
 
High Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practicesHigh Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practices
 
The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...
 
Performace optimization (increase website speed)
Performace optimization (increase website speed)Performace optimization (increase website speed)
Performace optimization (increase website speed)
 
A Holistic View of Website Performance
A Holistic View of Website PerformanceA Holistic View of Website Performance
A Holistic View of Website Performance
 
Front-end performances
Front-end performancesFront-end performances
Front-end performances
 
High performance website
High performance websiteHigh performance website
High performance website
 
High Performance Websites
High Performance WebsitesHigh Performance Websites
High Performance Websites
 
Optimising Web Application Frontend
Optimising Web Application FrontendOptimising Web Application Frontend
Optimising Web Application Frontend
 
DrupalCampLA 2011 - Drupal frontend-optimizing
DrupalCampLA 2011 - Drupal frontend-optimizingDrupalCampLA 2011 - Drupal frontend-optimizing
DrupalCampLA 2011 - Drupal frontend-optimizing
 
7 Habits of Exceptional Performance
7 Habits of Exceptional Performance7 Habits of Exceptional Performance
7 Habits of Exceptional Performance
 
Heavy Web Optimization: Frontend
Heavy Web Optimization: FrontendHeavy Web Optimization: Frontend
Heavy Web Optimization: Frontend
 
Website Performance
Website PerformanceWebsite Performance
Website Performance
 
Performance tuning of Websites
Performance tuning of WebsitesPerformance tuning of Websites
Performance tuning of Websites
 
High-Speed HTML5
High-Speed HTML5High-Speed HTML5
High-Speed HTML5
 
The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013The Need for Speed - SMX Sydney 2013
The Need for Speed - SMX Sydney 2013
 
Web Client Performance
Web Client PerformanceWeb Client Performance
Web Client Performance
 
Csdn Drdobbs Tenni Theurer Yahoo
Csdn Drdobbs Tenni Theurer YahooCsdn Drdobbs Tenni Theurer Yahoo
Csdn Drdobbs Tenni Theurer Yahoo
 
SearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital Marketers
SearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital MarketersSearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital Marketers
SearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital Marketers
 

Recently uploaded

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

High Performance Ajax Applications

  • 1.
  • 2. High Performance Ajax Applications Siarhei Barysiuk s.barysiuk@sam-solutions.net
  • 4. 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?
  • 5.
  • 6. Best Practices from Yahoo! 34 best practices divided into 7 categories. • Content • Server • Cookie • CSS • JavaScript • Images • Mobile
  • 8. 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
  • 9. 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!
  • 10. 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.
  • 11. 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
  • 12. Server: Add an Expires or a Cache-Control Header Loading http://www.yahoo.com with an empty cache a full cache
  • 13. Server: Gzip Components Accept-Encoding: gzip, deflate Content-Encoding: gzip
  • 14. Server: Gzip Components Gzipping generally reduces the response size by about 70%. Apache 1.3 mod-gzip Apache 2.0 mod-deflate IIS ...
  • 15. 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
  • 16. 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.
  • 17. 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.
  • 20. 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
  • 21. 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
  • 22. 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.
  • 23. 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.
  • 24. 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.
  • 25. 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)
  • 26. 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.
  • 27. Content: Reduce the Number of DOM Elements
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. Content: Minimize the Number of iframes Demo
  • 35. Cookie 1. Reduce Cookie Size 2. Use Cookie-free Domains for Components
  • 36. 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;
  • 37. Cookie: Reduce Cookie Size 2x Response times for various cookie sizes
  • 38. Cookie: Reduce Cookie Size Analysis of Cookie Sizes across the Web Total Cookie Sizes *(for home page)
  • 39. 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.
  • 40. 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
  • 42. CSS
  • 43. CSS 1. Put Stylesheets at the Top 2. Avoid CSS Expressions 3. Choose <link> over @import 4. Avoid Filters
  • 44. 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.
  • 45. 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.
  • 46. 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.
  • 47. 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
  • 50. 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
  • 51. 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
  • 52. 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
  • 53. 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; }
  • 54. 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)
  • 55. 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.
  • 56. 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
  • 57. 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>
  • 59. ... more JavaScript performance
  • 60. 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
  • 61. 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; } }
  • 62. 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
  • 63. 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
  • 66. Images 1. Optimize Images 2. Optimize CSS Sprites 3. Don't Scale Images in HTML 4. Make favicon.ico Small and Cacheable
  • 68. 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
  • 69. Images: Optimize CSS Sprites Demo
  • 70. 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.
  • 71. 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
  • 73. Tools