SlideShare a Scribd company logo
Performance
       Measurements and
       Optimization
       Why You Should Care

       Page Load Optimizations

       JavaScript Optimizations

       CSS Optimizations




Saturday, January 26, 13
About Me



       • Ynon Perek


       • ynon@ynonperek.com


       • Slides are available from:


             • http://ynonperek.com




Saturday, January 26, 13
Awesome Resources

       • Ilya Grigorik’s free performance crash course
         http://www.igvita.com/2013/01/15/faster-websites-crash-course-on-web-
         performance/


       • Web Performance Today Blog:
         http://www.webperformancetoday.com/


       • Steve Souders Blog and Books:
         http://stevesouders.com/




Saturday, January 26, 13
Facts & Stats




    “              47% of consumer   s expect a web      ”
                           load in 2 seco nds or less.
                   page to




Saturday, January 26, 13
Facts & Stats




    “           73% of m   obile interne t users say
                                ncountered   a website
                                                         ”
                th at they’ve e
                tha t was too s  low to load.




Saturday, January 26, 13
Facts & Stats




                                        y In Page-
      “            Just One S econd Dela
                         Can Cause 7% Loss In
                                                     ”
                   Load
                   Customer C  onversions




Saturday, January 26, 13
How Load Time Affects Conversion Rate

       • Glasses Direct measured




Saturday, January 26, 13
How Load Time Affects Conversion Rate

       • Strangeloop measured




Saturday, January 26, 13
How Load Time Affects Conversion Rate

       • Wallmart measured




Saturday, January 26, 13
How Load Time Affects Conversion Rate

       • Google measured


                                         Duration
            Type Of Delay   Delay (ms)              Impact
                                         (weeks)

               Pre Header      50           4         -

               Pre Header      100          4       -0.2%

             Post Header       200          6       -0.59%

             Post Header       400          6       -0.59%


Saturday, January 26, 13
How Load Time Affects Your Mood


       • Harris Interactive asked


       • 84% had problems.


       • Here’s what they did




Saturday, January 26, 13
Web Performance: You Should Care

       • Page load time affects your bounce rate


       • Page load time affects time on site


       • Page load time affects conversion


       • Page load time affects user satisfaction




Saturday, January 26, 13
Web Performance Stats (Retailers)


                   Website                            Load Time (In Seconds)

                   Barnes & Noble                                    4.88

                   Grainger                                          4.65

                   Buy.com                                           5.03

                   Amazon.com                                        6.31

                  Data from: http://www.keynote.com/keynote_competitive_research/
                  performance_indices/mobile/retail/index.html
Saturday, January 26, 13
What Is Page Load Time

                           Page Load Starts Here



                           GET data




                           Here It Is




Saturday, January 26, 13
What Affects Page Load

       • Network


       • Server Code


       • Number Of HTTP Requests


       • Size Of HTTP Responses


       • How Fast Is The Browser


       • Browser Decisions




Saturday, January 26, 13
Demo: Page Load cnn.com




Saturday, January 26, 13
cnn.com Takeaways

       • Site loading involves GETting over 100 resources


       • Most data is still images


       • Browser cache is misleading




Saturday, January 26, 13
Bandwidth Vs. Latency




Saturday, January 26, 13
Bandwidth Vs. Latency




Saturday, January 26, 13
Demo: Testing Latency With httping




Saturday, January 26, 13
Q&A




Saturday, January 26, 13
Optimizing Page
       Load
       HTTP Basics
       Reduce # Of Requests
       Reduce Distance
       Reduce Size




Saturday, January 26, 13
HTTP Basics

       • Verify using HTTP 1.1 and Keepalive


       • Verify using GZip compression


       • Can use chrome or:


       • curl -I --compressed http://yoursite.com




Saturday, January 26, 13
Using CSS Sprites To Reduce Images

       • Group all small images into one large image called sprite sheet


       • Use CSS code to “cut” the relevant pieces of the sprite sheet




Saturday, January 26, 13
Using CSS Sprites To Reduce Images

       • Demo: Use http://www.spritecow.com/ to generate a new sprite sheet




Saturday, January 26, 13
Inline Images Using Data URLs

        data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHQAAAB0CAIAAADb
        +IFwAAAABmJLR0QA/wD/AP+gvaeTAAADLklEQVR4nO2dwZLjMAgFN1vz/
        7+cuemiCgZEx5lU9zGWLecVIghw/Hg+n/+E4f/dN/DNKC6I4oIoLojigiguiOKC/Lw68Hg8Tq67h8/
        rgkFkHYw5vJ/MjU1dcKHlgiguyEu3sCjtj/
        clFiy6zHrcx2S8SmbwzuE33dFyQRQX5NotLIKFECyodWidnlm8e9gQOJw1JhgcnBWM2Sm5Di0XRHFB
        Cm6hR+AEdkeRifAz63qf4paagJYLorgguFsoRQI9/5DhFv+g5YIoLkjBLfQWVGk9BruA3sa/
        d89TrkPLBVFckGu3MFUC6BFsB6Y+WYx/
        Uy0XRHFBHjc24o2HBJk8hpuIL0FxQWb6FjIlgMPTS1Nk6hfB4F6wsaPlgiguyPuihU
        +L8HsrvRThaLkgigty7RZKbQb7mKnTS66jt8CDO+yh5YIoLkghWpgKv3dKRcxe71Mv/
        DhMTWi5IIoL8tItlNZ1wBs2CIdTTFVFd7RcEMUF6eQWev3Dh7uAqX3K4SFzC5+C4oIU+hZ6oX4vnu/
        VQXbG26ozky60XBDFBbneRAQcJvNvaUMqxSHBPWfQckEUF6RQieg9crgYTxWWnNJhwjNzaEfLBVFc
        kEI702FFr/fkY+n0Ke80VQzVckEUF6TwNyxTVb/
        SlQ8zGwGHpRajhZtRXJDOJqL0w801HvTueadXzcyg5YIoLsj1JiKzsjKHenF4L6LYL9j7FuYWPhfFBRkuUA
        anZyg5it5ch5WI/RNzC/eguCCFLsfMmN7CjO7vrE5a2p70vnKAlguiuCDDf9o2lf0rTZEpmgT
        +oddamUHLBVFckM4zEeMNRcF1pmqFU49dlCbVckEUF+RltBBk7TKDF+8sWQaTHp5ul
        +PHobgg73urVIapZEUpnuH2O1ouiOKC4G+VKqXvuL6FqSuXog4tF0RxQfC3SgXLp5TiG28qGC
        +a7Gi5IIoLgr8+pkRp7zDlKGx+/
        pMoLshnuYXeHy9MeYPxLmgtF0RxQfC3Si2mfrinkpnBpL2ay46WC6K4IDe8Var37BXXwDD
        +PPVCywVRXJA73yr19Wi5IIoLorggiguiuCCKC6K4IIoL8gvjNAP/KJZ4+gAAAABJRU5ErkJggg==




Saturday, January 26, 13
Inline Images Using Data URLs

       • A data url is a base64 encoded version of the image bytes


       • Data URL basic form:

           data:[<mediatype>][;base64],<data>


       • Use server side code or http://websemantics.co.uk/online_tools/
         image_to_data_uri_convertor/ to generate


       • From Unix:
         echo -n 'data:image/png;base64,';base64 image.png




Saturday, January 26, 13
Why DataURLs are not awesome

       • They make your HTML ugly


       • They’re not saved in browser cache


       • No IE7 support


       • Image blocks page load


       • Larger in size (about 1.333%)




Saturday, January 26, 13
Use CSS3 Instead of Images

       • Replace onions with border-radius


       • Use css gradients instead of images


       • Use box-shadow instead of images


       • Tools:


             • http://css3generator.com/


             • http://www.colorzilla.com/gradient-editor/




Saturday, January 26, 13
Use CSS Shapes Instead Of Images




      <body>
          <div class="shape triangle-up red"></div>
          <p></p>
          <div class="shape triangle-down red"></div>
      </body>




Saturday, January 26, 13
Use CSS Shapes Instead Of Images

       .shape {
         border: 30px solid;
         width:0; height: 0;
       }
        
       .red { border-color: red; }
        
       .triangle-up {
         border-left-color: transparent;
         border-top-color: transparent;
         border-right-color: transparent;
       }
        
       .triangle-down {
         border-left-color: transparent;
         border-bottom-color: transparent;
         border-right-color: transparent;
       }

Saturday, January 26, 13
More CSS Shapes
       http://css-tricks.com/examples/ShapesOfCSS/




Saturday, January 26, 13
Old Browsers Fallback

       • Old browsers may not support CSS shapes


       • Use Modernizr to detect and fallback


     .no-js .glossy,
     .no-cssgradients .glossy {
         background: url("images/glossybutton.png");
     }
      
     .cssgradients .glossy {
         background-image: linear-gradient(top, #555, #333);
     }




Saturday, January 26, 13
Combine Scripts And Stylesheets

       • Combine multiple JS into a single script


       • Combine multiple CSS files into a single stylesheet


       • Ideal: Use one stylesheet and one script per page


       • Tools:


             • http://yui.github.com/yuicompressor/


             • http://yeoman.io/




Saturday, January 26, 13
Avoid Redirects At All Cost

       • Redirects add another request but with no value


       • Worst kind: Mobile Redirects


       • Demo: d.co.il




Saturday, January 26, 13
Avoid Redirects At All Cost

       • Better Way: Offer users to download the app
         from your web page


       • iOS 6 has the option built-in (smart app banners):

          <meta name="apple-itunes-app" content="app-id=366977202">




       • Or use the jQuery Plugin:
         http://jasny.github.com/jquery.smartbanner/#android




Saturday, January 26, 13
Use Cache To Reduce # Of Requests

       • No Request is better than fast request   File size doesn’t matter
       • Browser Cache Is Your Friend




Saturday, January 26, 13
Cache Headers

       • HTTP 1.0 Had an Expires header:

           Expires: Thu, 15 Apr 2010 20:00:00 GMT


       • HTTP 1.1 Added Cache-Control header:

           Cache-Control: max-age=315360000




Saturday, January 26, 13
Caching vs. Inlining

       • Use external CSS and JavaScript for most web sites to allow caching


       • Use inline CSS and JavaScript for pages that are only visited once (for
         example: landing pages)




      <style>                  <head>
        h1 {                       <title>Canvas Color Picker</title>
          color: red            
        }                          <link rel="stylesheet" href="style.css" /> 
      </style>                 </head>




Saturday, January 26, 13
Reduce Distance


                           Closer => Lower RTT




Saturday, January 26, 13
Reduce Distance

       • Consider using a local server


       • Use a CDN


       • Demo: Loading jQuery from CDN vs. Non-local server




Saturday, January 26, 13
Reduce Size

       • Minify JS and CSS


       • Use GZip Compression


       • Split Payload


       • Optimize Images




Saturday, January 26, 13
Help Thy Browser
       Flush Early
       Place Scripts At The Bottom
       Place Stylesheets At The Top
       Shard Dominant Domains




Saturday, January 26, 13
Flushing Early

       • Web browsers try to do their best to load resources in parallel.


       • Send some data first, and browser will start rendering


        <html>
          <head>
            <title>HeadFirst</title>
            <link rel="stylesheet" href="style.css" />
          </head>
         
          <body>
            <p>Intro Text</p>
            <!-- long running server code -->
          </body>
        </html>



Saturday, January 26, 13
Demo
       https://gist.github.com/4636526




Saturday, January 26, 13
Flush Early Caveats

       • Verify presence of “Transfer-Encoding=chunked” header


       • Verify header is long enough


             • Chrome has a minimum threshold of ~2KB


             • Safari has a minimum threshold of ~1KB


       • Verify output buffering is off in php
         (or use ob_ functions)




Saturday, January 26, 13
Place Scripts At The Bottom

       • Scripts block rendering when they execute


       • By placing them at the bottom, browser can display prior data


       • Demo Blocking Script Tag


       • Note: Some browsers won’t start downloading ANYTHING while script tags
         are in queue




Saturday, January 26, 13
Defer vs. Async Scripts

       • Defer downloads in parallel, executes by order


       • Async downloads in parallel, executes when ready


       • Use async if possible


       • Best: Use require.js




Saturday, January 26, 13
Place Stylesheets At The Bottom



       • No rendering is done before     <html>
         stylesheets are ready             <head>
                                             <title>HeadFirst</title>
                                             <link rel="stylesheet"
       • Placing them at the top hints
                                         href="style.css" />
         the browser to download first
                                           </head>

       • Alternative: FOUC. Demo           <body>
         http://stevesouders.com/hpws/       <p>Intro Text</p>
                                           </body>
         css-fouc.php
                                         </html>




Saturday, January 26, 13
Shard Dominant Domains

       • Don’t automatically shard


       • Find critical path using https://
         developers.google.com/speed/
         pagespeed/


       • Sharding adds DNS work


       • Usually 2 domains are enough




Saturday, January 26, 13
Q&A




Saturday, January 26, 13
Optimize Site
       Responsiveness
       How To Measure Responsiveness
       Use Short Event Handlers
       Prefer CSS3 Transitions over JS
       Avoid Expensive JS
       Simplify CSS Selectors




Saturday, January 26, 13
Measuring Responsiveness

       • Use Chrome Developer Tools, Timeline tab


       • Keep event handlers < 100ms




Saturday, January 26, 13
Use JSPerf But Don’t Take It Too Seriously




Saturday, January 26, 13
Binding Vs. Delegating

       • When you have a long list or table, should you bind event handler on the
         parent or on each element ?




Saturday, January 26, 13
Binding vs. Delegating

       • Event handler is faster if bound directly on the element


       • Adding new elements is faster if bound on the container


       • Flip side: Less event handlers => Less memory


       • Tip: Be cautious with delegation




Saturday, January 26, 13
Prefer CSS3 Transitions Over JavaScript



       • They’re hardware accelerated        div {
                                               -webkit-transition: all 0.2s;
                                               -moz-transition: all 0.2s;
       • They don’t involve event handlers     -o-transition: all 0.2s;
                                               transition: all 0.2s;
                                             }
       • They’re easier to write




Saturday, January 26, 13
Avoid Expensive JavaScript

       • A browser saves its data in multiple data models


       • Some JavaScript calls require syncing these models


       • Find and mitigate using Chrome Developer Tools


       • Demo




Saturday, January 26, 13
Simplify CSS Selectors

       • Browsers need to match CSS rules to elements


       • The less matching attempts => The more efficient is the rule


       div {
         overflow: hidden;
       }
        <body>
          <div></div>
          <div class="one"></div>
          <div id="two"></div>
        </body>

Saturday, January 26, 13
Selectors Ordered By Complexity
       • Most Simple: ID Selectors ( #wrapper { ... } )


       • Class Selectors ( .item { ... } )


       • Type Selectors ( a { ... } )


       • Adjacent Sibling ( h1 + #wrapper { ... } )


       • Child Selectors ( #toc > li {...} )


       • Descendants Selector ( ul li { ... } )


       • Universal Selector ( * { ... } )


       • Attribute Selector ( [href=”#home”] { ... } )


       • Pseudo-Classes / Elements ( a:hover { ... } )



Saturday, January 26, 13
How Browsers Read Selectors

       • Selectors are parsed right-to-left


       • #top-menu a {...} finds all a elements on the page, and checks if they
         are under a #top-menu element


       • Try to use the most specific right part of a rule


       • a.menu-item is better




Saturday, January 26, 13
CSS Selectors
       Guidelines
       Avoid Universal Rules
       Don’t Qualify ID Selectors
       Don’t Qualify Class Selectors
       Use Specific Rules
       Avoid Descendants Selectors
       Avoid Tag-Child Selectors
       Use Less CSS




Saturday, January 26, 13
Avoid Universal Rules

       • Try to minimize using selectors other than:
         ID, class and tag




      a[href $= “pdf”] { ... }                         a.pdf { ... }




Saturday, January 26, 13
Don’t Qualify ID Selectors

       • It’s simply unnecessary


       • There’s only one element with that ID




                     div#wrapper                 #wrapper




Saturday, January 26, 13
Don’t Qualify Class Selectors

       • Extend the class name to be more specific instead


       • Classes are indexed, so class-only search is faster




                     ul.tasks                                  .task-list




Saturday, January 26, 13
Use Specific Rules

       • Long lists give the browser a hard time




                     ol li a                       .list-anchor




Saturday, January 26, 13
Avoid Descendant Selectors

       • They’re expensive, because search is done right-to-left




                     ol li a                                 .list-anchor




Saturday, January 26, 13
Avoid Tag Child Selectors




            #menu > li > a         .menu-item




Saturday, January 26, 13
Minimize CSS Rule Content

       • Can set a property on the parent and have it inherited to contained elements




      ul li {                                           ul {
        list-style-image: ...                             list-style-image: ...
      }                                                 }




Saturday, January 26, 13
Now Forget Everything




Saturday, January 26, 13
Performance Bottom Line

       • “97% of the time: premature optimization is the root of all evil”
          --- Donald Knuth


       • Only optimize what you need, when you need it


       • Consider performance from day 1


       • Measure business impact using Google Analytics




Saturday, January 26, 13
Thanks For Listening



       • Ynon Perek


       • ynon@ynonperek.com


       • Slides are available from:


             • http://ynonperek.com




Saturday, January 26, 13

More Related Content

PDF
Web Performance in the Age of HTTP2 - Topconf Tallinn 2016 - Holger Bartel
PDF
Web Performance Workshop - Velocity London 2013
PDF
Making Mobile Sites Faster
PDF
Are Today’s Good Practices… Tomorrow’s Performance Anti-Patterns?
PPT
The Need For Speed
KEY
Speed is Essential for a Great Web Experience
PDF
Voices that matter: High Performance Web Sites
PDF
Wcoc preso
Web Performance in the Age of HTTP2 - Topconf Tallinn 2016 - Holger Bartel
Web Performance Workshop - Velocity London 2013
Making Mobile Sites Faster
Are Today’s Good Practices… Tomorrow’s Performance Anti-Patterns?
The Need For Speed
Speed is Essential for a Great Web Experience
Voices that matter: High Performance Web Sites
Wcoc preso

What's hot (12)

PDF
Real World Web Standards
KEY
Sniffing the Mobile Context
PPT
Csdn Drdobbs Tenni Theurer Yahoo
PDF
Hacking Web Performance
PDF
PAC 2019 virtual Joerek Van Gaalen
PPTX
Cloud Connect Santa Clara 2013: Web Acceleration and Front-End Optimization (...
PPT
High Performance Websites By Souders Steve
PPT
High Performance Web Sites
PPT
Plop
PDF
Proven ways to improve your website performance optimizing front end and back...
PDF
Boston Web Performance Meetup: The Render Chain and You
PDF
Are Today’s Good Practices... Tomorrow’s Performance Anti-Patterns?
Real World Web Standards
Sniffing the Mobile Context
Csdn Drdobbs Tenni Theurer Yahoo
Hacking Web Performance
PAC 2019 virtual Joerek Van Gaalen
Cloud Connect Santa Clara 2013: Web Acceleration and Front-End Optimization (...
High Performance Websites By Souders Steve
High Performance Web Sites
Plop
Proven ways to improve your website performance optimizing front end and back...
Boston Web Performance Meetup: The Render Chain and You
Are Today’s Good Practices... Tomorrow’s Performance Anti-Patterns?
Ad

Viewers also liked (20)

PDF
Writing Reusable Web Components with jQuery and jQuery UI
PDF
02 JavaScript Syntax
PDF
Web Programming Intro
PDF
Html5 intro
PDF
01 Mobile Web Introduction
PPTX
основні теги мови Html
PPT
Диплом программиста получают в Витебском госуниверситете
PDF
Intro to SVGs
PDF
PDF
Scalable JavaScript
PDF
маркетинг кит - Seo - email version (01.01.2015)
PDF
Html5 apis
PDF
Услуга SEO
PDF
03 Advanced JavaScript
PDF
Frontend Engineer Toolbox
PDF
SEO-аудит своими силами / Вебинар WebPromoExperts
PDF
Regexp
PDF
08 ajax
PDF
JavaScript DOM Manipulations
PPTX
Презентация на тему "WEB-программирование"
Writing Reusable Web Components with jQuery and jQuery UI
02 JavaScript Syntax
Web Programming Intro
Html5 intro
01 Mobile Web Introduction
основні теги мови Html
Диплом программиста получают в Витебском госуниверситете
Intro to SVGs
Scalable JavaScript
маркетинг кит - Seo - email version (01.01.2015)
Html5 apis
Услуга SEO
03 Advanced JavaScript
Frontend Engineer Toolbox
SEO-аудит своими силами / Вебинар WebPromoExperts
Regexp
08 ajax
JavaScript DOM Manipulations
Презентация на тему "WEB-программирование"
Ad

Similar to Performance (20)

PDF
High Performance Websites
PPTX
SearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital Marketers
PDF
Let's speed it up a bit (AmsterdamPHP)
PDF
Web performance optimization
PDF
Speed is Essential for a Great Web Experience (Canvas Conf Version)
PPTX
Web Performance 101
PDF
7 Habits of Exceptional Performance
PDF
A little journey into website optimization
PPT
Performance engineering
PDF
MeasureWorks - Social Mentions as a Performance KPI
PDF
High Performance Mobile Web
PDF
Saving the Marriage (Between your Website and the User)
PDF
The Need For Speed - Rigor's slides from ShopVisible Client Connect 2012
PDF
Client-side Web Performance Optimization [paper]
KEY
Faster Frontends
PPTX
Website Performance
PPTX
Why your slow loading website is costing you sales and how to fix it
PPTX
Why your slow loading website is costing you sales and how to fix it
PPTX
10 things you can do to speed up your web app today stir trek edition
PPT
High Performance Websites
SearchLove San Diego 2018 | Mat Clayton | Site Speed for Digital Marketers
Let's speed it up a bit (AmsterdamPHP)
Web performance optimization
Speed is Essential for a Great Web Experience (Canvas Conf Version)
Web Performance 101
7 Habits of Exceptional Performance
A little journey into website optimization
Performance engineering
MeasureWorks - Social Mentions as a Performance KPI
High Performance Mobile Web
Saving the Marriage (Between your Website and the User)
The Need For Speed - Rigor's slides from ShopVisible Client Connect 2012
Client-side Web Performance Optimization [paper]
Faster Frontends
Website Performance
Why your slow loading website is costing you sales and how to fix it
Why your slow loading website is costing you sales and how to fix it
10 things you can do to speed up your web app today stir trek edition

More from Ynon Perek (20)

PDF
Html5 intro
PDF
09 performance
PDF
Mobile Web Intro
PDF
Qt multi threads
PDF
Vimperl
PDF
Syllabus
PDF
Mobile Devices
PDF
Network
PDF
Architecture app
PDF
Cryptography
PDF
Unit Testing JavaScript Applications
PDF
How to write easy-to-test JavaScript
PDF
Introduction to Selenium and Ruby
PDF
Introduction To Web Application Testing
PDF
Accessibility
PDF
Angularjs
PDF
Js memory
PDF
Qt Design Patterns
PDF
Web Application Security
PDF
Mongodb Intro
Html5 intro
09 performance
Mobile Web Intro
Qt multi threads
Vimperl
Syllabus
Mobile Devices
Network
Architecture app
Cryptography
Unit Testing JavaScript Applications
How to write easy-to-test JavaScript
Introduction to Selenium and Ruby
Introduction To Web Application Testing
Accessibility
Angularjs
Js memory
Qt Design Patterns
Web Application Security
Mongodb Intro

Performance

  • 1. Performance Measurements and Optimization Why You Should Care Page Load Optimizations JavaScript Optimizations CSS Optimizations Saturday, January 26, 13
  • 2. About Me • Ynon Perek • ynon@ynonperek.com • Slides are available from: • http://ynonperek.com Saturday, January 26, 13
  • 3. Awesome Resources • Ilya Grigorik’s free performance crash course http://www.igvita.com/2013/01/15/faster-websites-crash-course-on-web- performance/ • Web Performance Today Blog: http://www.webperformancetoday.com/ • Steve Souders Blog and Books: http://stevesouders.com/ Saturday, January 26, 13
  • 4. Facts & Stats “ 47% of consumer s expect a web ” load in 2 seco nds or less. page to Saturday, January 26, 13
  • 5. Facts & Stats “ 73% of m obile interne t users say ncountered a website ” th at they’ve e tha t was too s low to load. Saturday, January 26, 13
  • 6. Facts & Stats y In Page- “ Just One S econd Dela Can Cause 7% Loss In ” Load Customer C onversions Saturday, January 26, 13
  • 7. How Load Time Affects Conversion Rate • Glasses Direct measured Saturday, January 26, 13
  • 8. How Load Time Affects Conversion Rate • Strangeloop measured Saturday, January 26, 13
  • 9. How Load Time Affects Conversion Rate • Wallmart measured Saturday, January 26, 13
  • 10. How Load Time Affects Conversion Rate • Google measured Duration Type Of Delay Delay (ms) Impact (weeks) Pre Header 50 4 - Pre Header 100 4 -0.2% Post Header 200 6 -0.59% Post Header 400 6 -0.59% Saturday, January 26, 13
  • 11. How Load Time Affects Your Mood • Harris Interactive asked • 84% had problems. • Here’s what they did Saturday, January 26, 13
  • 12. Web Performance: You Should Care • Page load time affects your bounce rate • Page load time affects time on site • Page load time affects conversion • Page load time affects user satisfaction Saturday, January 26, 13
  • 13. Web Performance Stats (Retailers) Website Load Time (In Seconds) Barnes & Noble 4.88 Grainger 4.65 Buy.com 5.03 Amazon.com 6.31 Data from: http://www.keynote.com/keynote_competitive_research/ performance_indices/mobile/retail/index.html Saturday, January 26, 13
  • 14. What Is Page Load Time Page Load Starts Here GET data Here It Is Saturday, January 26, 13
  • 15. What Affects Page Load • Network • Server Code • Number Of HTTP Requests • Size Of HTTP Responses • How Fast Is The Browser • Browser Decisions Saturday, January 26, 13
  • 16. Demo: Page Load cnn.com Saturday, January 26, 13
  • 17. cnn.com Takeaways • Site loading involves GETting over 100 resources • Most data is still images • Browser cache is misleading Saturday, January 26, 13
  • 20. Demo: Testing Latency With httping Saturday, January 26, 13
  • 22. Optimizing Page Load HTTP Basics Reduce # Of Requests Reduce Distance Reduce Size Saturday, January 26, 13
  • 23. HTTP Basics • Verify using HTTP 1.1 and Keepalive • Verify using GZip compression • Can use chrome or: • curl -I --compressed http://yoursite.com Saturday, January 26, 13
  • 24. Using CSS Sprites To Reduce Images • Group all small images into one large image called sprite sheet • Use CSS code to “cut” the relevant pieces of the sprite sheet Saturday, January 26, 13
  • 25. Using CSS Sprites To Reduce Images • Demo: Use http://www.spritecow.com/ to generate a new sprite sheet Saturday, January 26, 13
  • 26. Inline Images Using Data URLs data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHQAAAB0CAIAAADb +IFwAAAABmJLR0QA/wD/AP+gvaeTAAADLklEQVR4nO2dwZLjMAgFN1vz/ 7+cuemiCgZEx5lU9zGWLecVIghw/Hg+n/+E4f/dN/DNKC6I4oIoLojigiguiOKC/Lw68Hg8Tq67h8/ rgkFkHYw5vJ/MjU1dcKHlgiguyEu3sCjtj/ clFiy6zHrcx2S8SmbwzuE33dFyQRQX5NotLIKFECyodWidnlm8e9gQOJw1JhgcnBWM2Sm5Di0XRHFB Cm6hR+AEdkeRifAz63qf4paagJYLorgguFsoRQI9/5DhFv+g5YIoLkjBLfQWVGk9BruA3sa/ d89TrkPLBVFckGu3MFUC6BFsB6Y+WYx/ Uy0XRHFBHjc24o2HBJk8hpuIL0FxQWb6FjIlgMPTS1Nk6hfB4F6wsaPlgiguyPuihU +L8HsrvRThaLkgigty7RZKbQb7mKnTS66jt8CDO+yh5YIoLkghWpgKv3dKRcxe71Mv/ DhMTWi5IIoL8tItlNZ1wBs2CIdTTFVFd7RcEMUF6eQWev3Dh7uAqX3K4SFzC5+C4oIU+hZ6oX4vnu/ VQXbG26ozky60XBDFBbneRAQcJvNvaUMqxSHBPWfQckEUF6RQieg9crgYTxWWnNJhwjNzaEfLBVFc kEI702FFr/fkY+n0Ke80VQzVckEUF6TwNyxTVb/ SlQ8zGwGHpRajhZtRXJDOJqL0w801HvTueadXzcyg5YIoLsj1JiKzsjKHenF4L6LYL9j7FuYWPhfFBRkuUA anZyg5it5ch5WI/RNzC/eguCCFLsfMmN7CjO7vrE5a2p70vnKAlguiuCDDf9o2lf0rTZEpmgT +oddamUHLBVFckM4zEeMNRcF1pmqFU49dlCbVckEUF+RltBBk7TKDF+8sWQaTHp5ul +PHobgg73urVIapZEUpnuH2O1ouiOKC4G+VKqXvuL6FqSuXog4tF0RxQfC3SgXLp5TiG28qGC +a7Gi5IIoLgr8+pkRp7zDlKGx+/ pMoLshnuYXeHy9MeYPxLmgtF0RxQfC3Si2mfrinkpnBpL2ay46WC6K4IDe8Var37BXXwDD +PPVCywVRXJA73yr19Wi5IIoLorggiguiuCCKC6K4IIoL8gvjNAP/KJZ4+gAAAABJRU5ErkJggg== Saturday, January 26, 13
  • 27. Inline Images Using Data URLs • A data url is a base64 encoded version of the image bytes • Data URL basic form: data:[<mediatype>][;base64],<data> • Use server side code or http://websemantics.co.uk/online_tools/ image_to_data_uri_convertor/ to generate • From Unix: echo -n 'data:image/png;base64,';base64 image.png Saturday, January 26, 13
  • 28. Why DataURLs are not awesome • They make your HTML ugly • They’re not saved in browser cache • No IE7 support • Image blocks page load • Larger in size (about 1.333%) Saturday, January 26, 13
  • 29. Use CSS3 Instead of Images • Replace onions with border-radius • Use css gradients instead of images • Use box-shadow instead of images • Tools: • http://css3generator.com/ • http://www.colorzilla.com/gradient-editor/ Saturday, January 26, 13
  • 30. Use CSS Shapes Instead Of Images <body>     <div class="shape triangle-up red"></div>     <p></p>     <div class="shape triangle-down red"></div> </body> Saturday, January 26, 13
  • 31. Use CSS Shapes Instead Of Images .shape {   border: 30px solid;   width:0; height: 0; }   .red { border-color: red; }   .triangle-up {   border-left-color: transparent;   border-top-color: transparent;   border-right-color: transparent; }   .triangle-down { border-left-color: transparent; border-bottom-color: transparent; border-right-color: transparent; } Saturday, January 26, 13
  • 32. More CSS Shapes http://css-tricks.com/examples/ShapesOfCSS/ Saturday, January 26, 13
  • 33. Old Browsers Fallback • Old browsers may not support CSS shapes • Use Modernizr to detect and fallback .no-js .glossy, .no-cssgradients .glossy {     background: url("images/glossybutton.png"); }   .cssgradients .glossy {     background-image: linear-gradient(top, #555, #333); } Saturday, January 26, 13
  • 34. Combine Scripts And Stylesheets • Combine multiple JS into a single script • Combine multiple CSS files into a single stylesheet • Ideal: Use one stylesheet and one script per page • Tools: • http://yui.github.com/yuicompressor/ • http://yeoman.io/ Saturday, January 26, 13
  • 35. Avoid Redirects At All Cost • Redirects add another request but with no value • Worst kind: Mobile Redirects • Demo: d.co.il Saturday, January 26, 13
  • 36. Avoid Redirects At All Cost • Better Way: Offer users to download the app from your web page • iOS 6 has the option built-in (smart app banners): <meta name="apple-itunes-app" content="app-id=366977202"> • Or use the jQuery Plugin: http://jasny.github.com/jquery.smartbanner/#android Saturday, January 26, 13
  • 37. Use Cache To Reduce # Of Requests • No Request is better than fast request File size doesn’t matter • Browser Cache Is Your Friend Saturday, January 26, 13
  • 38. Cache Headers • HTTP 1.0 Had an Expires header: Expires: Thu, 15 Apr 2010 20:00:00 GMT • HTTP 1.1 Added Cache-Control header: Cache-Control: max-age=315360000 Saturday, January 26, 13
  • 39. Caching vs. Inlining • Use external CSS and JavaScript for most web sites to allow caching • Use inline CSS and JavaScript for pages that are only visited once (for example: landing pages) <style> <head> h1 {     <title>Canvas Color Picker</title> color: red   }     <link rel="stylesheet" href="style.css" />  </style> </head> Saturday, January 26, 13
  • 40. Reduce Distance Closer => Lower RTT Saturday, January 26, 13
  • 41. Reduce Distance • Consider using a local server • Use a CDN • Demo: Loading jQuery from CDN vs. Non-local server Saturday, January 26, 13
  • 42. Reduce Size • Minify JS and CSS • Use GZip Compression • Split Payload • Optimize Images Saturday, January 26, 13
  • 43. Help Thy Browser Flush Early Place Scripts At The Bottom Place Stylesheets At The Top Shard Dominant Domains Saturday, January 26, 13
  • 44. Flushing Early • Web browsers try to do their best to load resources in parallel. • Send some data first, and browser will start rendering <html>   <head>     <title>HeadFirst</title>     <link rel="stylesheet" href="style.css" />   </head>     <body>     <p>Intro Text</p>     <!-- long running server code -->   </body> </html> Saturday, January 26, 13
  • 45. Demo https://gist.github.com/4636526 Saturday, January 26, 13
  • 46. Flush Early Caveats • Verify presence of “Transfer-Encoding=chunked” header • Verify header is long enough • Chrome has a minimum threshold of ~2KB • Safari has a minimum threshold of ~1KB • Verify output buffering is off in php (or use ob_ functions) Saturday, January 26, 13
  • 47. Place Scripts At The Bottom • Scripts block rendering when they execute • By placing them at the bottom, browser can display prior data • Demo Blocking Script Tag • Note: Some browsers won’t start downloading ANYTHING while script tags are in queue Saturday, January 26, 13
  • 48. Defer vs. Async Scripts • Defer downloads in parallel, executes by order • Async downloads in parallel, executes when ready • Use async if possible • Best: Use require.js Saturday, January 26, 13
  • 49. Place Stylesheets At The Bottom • No rendering is done before <html> stylesheets are ready   <head>     <title>HeadFirst</title>     <link rel="stylesheet" • Placing them at the top hints href="style.css" /> the browser to download first   </head> • Alternative: FOUC. Demo   <body> http://stevesouders.com/hpws/     <p>Intro Text</p>   </body> css-fouc.php </html> Saturday, January 26, 13
  • 50. Shard Dominant Domains • Don’t automatically shard • Find critical path using https:// developers.google.com/speed/ pagespeed/ • Sharding adds DNS work • Usually 2 domains are enough Saturday, January 26, 13
  • 52. Optimize Site Responsiveness How To Measure Responsiveness Use Short Event Handlers Prefer CSS3 Transitions over JS Avoid Expensive JS Simplify CSS Selectors Saturday, January 26, 13
  • 53. Measuring Responsiveness • Use Chrome Developer Tools, Timeline tab • Keep event handlers < 100ms Saturday, January 26, 13
  • 54. Use JSPerf But Don’t Take It Too Seriously Saturday, January 26, 13
  • 55. Binding Vs. Delegating • When you have a long list or table, should you bind event handler on the parent or on each element ? Saturday, January 26, 13
  • 56. Binding vs. Delegating • Event handler is faster if bound directly on the element • Adding new elements is faster if bound on the container • Flip side: Less event handlers => Less memory • Tip: Be cautious with delegation Saturday, January 26, 13
  • 57. Prefer CSS3 Transitions Over JavaScript • They’re hardware accelerated div {   -webkit-transition: all 0.2s;   -moz-transition: all 0.2s; • They don’t involve event handlers   -o-transition: all 0.2s;   transition: all 0.2s; } • They’re easier to write Saturday, January 26, 13
  • 58. Avoid Expensive JavaScript • A browser saves its data in multiple data models • Some JavaScript calls require syncing these models • Find and mitigate using Chrome Developer Tools • Demo Saturday, January 26, 13
  • 59. Simplify CSS Selectors • Browsers need to match CSS rules to elements • The less matching attempts => The more efficient is the rule div {   overflow: hidden; } <body>   <div></div>   <div class="one"></div>   <div id="two"></div> </body> Saturday, January 26, 13
  • 60. Selectors Ordered By Complexity • Most Simple: ID Selectors ( #wrapper { ... } ) • Class Selectors ( .item { ... } ) • Type Selectors ( a { ... } ) • Adjacent Sibling ( h1 + #wrapper { ... } ) • Child Selectors ( #toc > li {...} ) • Descendants Selector ( ul li { ... } ) • Universal Selector ( * { ... } ) • Attribute Selector ( [href=”#home”] { ... } ) • Pseudo-Classes / Elements ( a:hover { ... } ) Saturday, January 26, 13
  • 61. How Browsers Read Selectors • Selectors are parsed right-to-left • #top-menu a {...} finds all a elements on the page, and checks if they are under a #top-menu element • Try to use the most specific right part of a rule • a.menu-item is better Saturday, January 26, 13
  • 62. CSS Selectors Guidelines Avoid Universal Rules Don’t Qualify ID Selectors Don’t Qualify Class Selectors Use Specific Rules Avoid Descendants Selectors Avoid Tag-Child Selectors Use Less CSS Saturday, January 26, 13
  • 63. Avoid Universal Rules • Try to minimize using selectors other than: ID, class and tag a[href $= “pdf”] { ... } a.pdf { ... } Saturday, January 26, 13
  • 64. Don’t Qualify ID Selectors • It’s simply unnecessary • There’s only one element with that ID div#wrapper #wrapper Saturday, January 26, 13
  • 65. Don’t Qualify Class Selectors • Extend the class name to be more specific instead • Classes are indexed, so class-only search is faster ul.tasks .task-list Saturday, January 26, 13
  • 66. Use Specific Rules • Long lists give the browser a hard time ol li a .list-anchor Saturday, January 26, 13
  • 67. Avoid Descendant Selectors • They’re expensive, because search is done right-to-left ol li a .list-anchor Saturday, January 26, 13
  • 68. Avoid Tag Child Selectors #menu > li > a .menu-item Saturday, January 26, 13
  • 69. Minimize CSS Rule Content • Can set a property on the parent and have it inherited to contained elements ul li { ul { list-style-image: ... list-style-image: ... } } Saturday, January 26, 13
  • 71. Performance Bottom Line • “97% of the time: premature optimization is the root of all evil” --- Donald Knuth • Only optimize what you need, when you need it • Consider performance from day 1 • Measure business impact using Google Analytics Saturday, January 26, 13
  • 72. Thanks For Listening • Ynon Perek • ynon@ynonperek.com • Slides are available from: • http://ynonperek.com Saturday, January 26, 13