SlideShare une entreprise Scribd logo
1  sur  50
Télécharger pour lire hors ligne
MOBILE WEB BEST
                     PRACTICES




http://about.me/jamesdbloom
http://blog.jamesdbloom.com   JamesDBloom
PERCENTAGE OF MOBILE WEB

  50%

  45%

  40%

  35%

  30%

  25%

  20%

  15%

  10%

    5%

    0%




http://www.tecmark.co.uk/wp-content/uploads/2011/08/Mobile-and-UK-Web-Traffic-August-2011.pdf
WHAT I’M TALKING ABOUT

¡  The Problem
   §  What’s different and hard about mobile
¡  The Solution
   §  Adaptive Techniques
       §    Mobile First
       §    Avoid JavaScript
       §    Device Detection
       §    Adaptive Design
       §    Progressive Enhancement
   §  High Performance
       §  Network
              §    Less Request
              §    Less Bytes
              §    Bandwidth Efficiency
              §    Less Latency
       §  Sof tware
              §  Faster Page Rendering
              §  Faster Interaction
       §  User
              §  Faster Interaction
              §  Improve Perception
¡  Tools
   §  Debugging
   §  Performance
   §  Emulators
WHAT’S MOBILE – THE PROBLEM

¡  Network
  §  Different types of network:
     §  GSM, GPRS, WCDMA, UMTS, EDGE, HSPA, UMTS, LTE, WiMAX
  §  High latencies
     §  300ms to 1000ms
  §  High packet loss
     §  From 0.1% to >20%
     §  Each time triggers TCP Slow Start again
  §  Radio Resource Control (RRC)
     §  Adds 1.5s to 2s to initiate connection
  §  Total Connection Time
     §  RRC + DNS + TCP 3-way handshake + TCP slow start + HTTP Request
     §  SSL adds even more
  §  Bandwidth
     §  3G
        §  Download: ~1Mbps   Upload: ~0.5 Mbps
     §  Broadband
        §  Download: ~9Mbps   Upload: ~2Mbps
WHAT’S MOBILE – THE PROBLEM

   ¡  Device
       §  Rapidly changing, widely diverse hardware
       §  “2500 different devices on Facebook per month” - Tobie Langel

       7000
                                        SunSpider JS Benchmark (in ms)
                                         for some of the devices released in the last year
       6000
       5000
       4000
       3000
       2000
        1000
            0




http://www.anandtech.com/show/5584/htcs-new-strategy-the-htc-one
WHAT’S MOBILE – THE PROBLEM

   ¡  Device
        §  Slow CPU
            §  10x slower then desktop
            §  JavaScript that runs for 100ms on desktop will take ~1s on mobile
        §  Low memory
            §  Mobile RAM in MB
            §  Desktop RAM in GB
        §  Small screen
        §  Navigation
            §  Touch
                §  Gestures: Tap, Double Tap, Drag, Flick, Pinch, Spread, Press, Press & Tap, Press & Drag,
                    Rotate, …
                §  More direct interaction
                §  But different on each device
            §  Focus
            §  Pointer

Google Tech Talk - November 10, 2011 - Guy Podjarny
WHAT’S MOBILE – THE PROBLEM

¡  Software
  §  Rapidly changing, widely diverse browsers and operating systems
   No
            Browser 
                 Creator 
         No
          Browser 
                 Creator 
    1
        Android Browser 
             Google 
          21
       Obigo Browser 
             Obigo AB 
    2
             Apollo
                Team Apollo
        22
         Opera Mini 
           Opera Software 
    3
      BlackBerry Browser 
       Research in Motion 
   23
        Opera Mobile 
          Opera Software 
    4
             Blazer 
                   Palm 
          24
            Palm
                     HP
    5
              Bada
                   Samsung
          25
            Pixo 
             Sun Microsystems 

    6
      Chrome for Android
             Google
           26
    PlayStation Portable
            Sony 

    7
           Classilla 
            Cameron Kaiser 
      27
      Polaris Browser 
            Infraware

    8
            Deepfish 
               Microsoft 
        28
           Safari 
                  Apple

    9
        Dolphin Browser 
             MoboTap 
         29
        Symbian / S60
               Nokia 
                                                              30
         Skweezer 
    10
      Firefox for mobile 
      Mozilla Foundation 
                                                              31
          Skyfire 
               Skyfire Labs
    11
         ibisBrowser 
                 ibis
                                                              32
   Skyfire Mobile Browser 
         Skyfire 
    12
   Internet Explorer Mobile 
       Microsoft 
                                                              33
           Steel 
    13
         Iris Browser 
           Torch Mobile 
                                                              34
          Teashark 
    14
             JOCA 
                 InteracT!V 
                                                              35
           Tristit 
    15
       Kindle Basic Web 
          Amazon.com 
                                                              36
        UC Browser 
               UC Mobile 
    16
             MIB
                   Motorola
    17
            Minimo 
            Mozilla Foundation 
   37
         uZard Web 
              Logicplant

    18
      Myriad / Openwave
          Myriad Group 
       38
   Vision Mobile Browser 
          Novarra 

    19
          NetFront 
                 ACCESS 
          39
      WebOS Browser 
                Palm

    20
   Nokia Series 40 Browser 
          Nokia 
          40
          WinWAP 
            Winwap Technologies
WHAT’S MOBILE – THE PROBLEM

¡  Sof tware
   §  Changing rapidly
   §  Different navigation method
      §  Proxied vs Direct
         §  Proxied – Opera Mini, Kindle Fire
         §  Direct – all others
      §  HTTP vs SPDY
         §  SPDY – Kindle Fire, Chrome for Android
         §  HTTP – all others
   §  Process models
      §  Multi Process – Chrome for Android
      §  Single Process - all others
   §  Small Cache
      §  2-4MB
   §  Connections
      §  Max Total
      §  Max per host
      §  Pipelined
         §  Multiple requests over a single socket without waiting for a response
         §  Problems with proxies and head-of-line blocking
WHAT’S MOBILE – THE PROBLEM

   ¡  Users
        §  Distracted
            §  i.e. walking down the street
        §  Shorter interactions
            §  i.e. waiting for a bus
        §  Touch
            §  Fat fingers
            §  Gestures (are they all intuitive?)
        §  Targeted tasks
            §  i.e. what are the local restaurants?
        §  Expectations
            §  Web that “pretends” to be app is likely to disappoint
            §  85% - “customers expect to be able to shop on their phones and want the
                experience to be as good or better than on a computer”


http://www.nytimes.com/2011/04/18/technology/18mobile.html?_r=3
MOBILE FIRST

¡  Mobile first
   §  Start simple and build up
   §  Test for presence (and function) of all APIs
     §  If it exists it may not work correctly
   §  Everything should fallback
     §  local storage → local variable → no storage
     §  push & pop state → hash bang fall → page refresh
     §  auto refresh → manual refresh button
   §  Avoid native events → use synthetic events
     §  minimizes difference between browsers
¡  Forget pixel perfect
   §  Fluid grids
   §  Adaptive design
AVOID JAVASCRIPT

¡  Avoid JS → Middle Tier
  §  Why are we re-implementing the browser?
  §  Maximize stability across devices, even unknown devices
  §  Ensure site works without JS
  §  You control execution environment
    §  More reliable
    §  Easier to test
       §  Limit device dependent code
    §  Easier to automate tests
       §  Simplify browser interaction helps Selenium
       §  More code covered by Java unit tests
    §  Easier to optimize
       §    Scale out / up
       §    Easier to diagnose issues
       §    Well understood
       §    Better tools
ADAPT – DEVICE DETECTION

¡  Breakpoints
  §  Major breakpoint on server
     §  Chose fixed high level breakpoints
        §    Mobile
        §    Tablet
        §    Desktop
        §    TV
     §  Avoid serving desktop site on mobile width
        §    Too heavy
        §    Too slow to download
        §    Too slow to render
        §    Not optimized correctly
     §  Adapt
        §    Content
        §    Layout
        §    Features
        §    Page weight
     §  Caching
        §  Vary: User-Agent!
ADAPT – DEVICE DETECTION

¡  Breakpoints
   §  How to select major breakpoint
      §  Headers
          §  User-Agent
          §  Accept
          §  x-wap-profile / Profile
             §  UAProfile with device capabilities and preferences (W3C Ubiquitous Web Applications Working Group – closed July 2010)
          §  OperaMini
      §  Device Libraries
          §  WURFL
             §  Open Source
             §  Slightly limited information
             §  Based on UAProfile
          §  DeviceAtlas
             §  Started by Ericsson, Google, GSM Association, Microsoft, Nokia, Samsung, T-Mobile, Telecom, Telecom Italia, Visa and Vodafone
          §  51Degrees
             §  Build into ASP.NET and MVC.NET
          §  DetectRight
      §  Custom DB
          §  Augment existing device library
             §  Log capabilities (i.e. cookie / analytics / JS)
      §  Tools
          §  Spring Mobile
             §  WURFL
          §  Apache Mobile Filter
             §  WURFL
             §  51Degrees
             §  DetectRight
ADAPT – ADAPTIVE DESIGN

¡  Breakpoints
  §  Minor breakpoint on client
     §  @media
        §  Screen size, resolution & pixel density
          §  Fluid grids, dif ferent columns, adapt image size (see earlier slide)
     §  navigator.connection.type!
        §  ETHERNET, WIFI, CELL_2G, CELL_3G, …!
     §  Send to server
        §  Cookie
        §  JS
     §  Landscape vs portrait
        §  Consider width of screen not width of viewport
     §  Test for presence (and function) of all APIs
        §  If it exists it may not work correctly
        §  Everything should fallback
          §  local storage → local variable → no storage
          §  push & pop state → hash bang fall → page refresh
          §  auto refresh → manual refresh button
  §  Indicate it’s a mobile website
ADAPT – PROGRESSIVE ENHANCEMENT

¡  Progressive Enhancement
  §  Test for presence (and function) of all
      APIs
    §  If it exists it may not work correctly
                                                                                          HTML5
    §  Everything should fallback
       §  local storage → local variable → no storage
       §  push & pop state → hash bang fall → page                                   AJAX / HIJAX
           refresh
       §  auto refresh → manual refresh button
  §  HTML5                                                                       CSS Extensions

    §  Not fully supported
       §    mobilehtml5.org
                                                                             Basic JavaScript
       §    www.modernizr.com
       §    caniuse.com
       §    www.browserscope.org                                      Advanced CSS
       §    www.quirksmode.org
    §  PolyFills                                               Simple CSS
       §  Add weight
       §  Better to except not supported and degrade    HTML
HIGH PERFORMANCE – WHY?

¡  47% expect page load < 2s
¡  40% abandon sites with page load > 3s
¡  +1s → -7% conversion rate
¡  if $100,000 per day, +1s → $2.5 million lost sales ever y year
¡  Bing
    §  +1s → -4% revenue
¡  Google
    §  0.4s to 0.9s → -25% searches (-$2.5 billion revenue)
¡  Firefox
    §  -2.2s download page → +15% downloads (+1.7 million extra / year)
¡  Shopzilla
    §  -5s → +7-12% revenue, -50% hardware cost
¡  Wallmart & Amazon
    §  every -100ms → +1% revenue
                                                                                           http://blog.kissmetrics.com/loading-time/
                                                                     http://blog.mozilla.com/metrics/category/website-optimization/
                                                              http://radar.oreilly.com/2009/07/velocity-making-your-site-fast.html
 http://www.webperformancetoday.com/2012/02/28/4-awesome-slides-showing-how-page-speed-correlates-to-business-metrics-at-walmart-com/
HIGH PERFORMANCE – LESS REQUESTS

   ¡  Less Requests
             0.5
                                      Highest Correlation to Load Time
            0.45


             0.4


            0.35
                    Total Requests   Image Requests   Total Xfer Size   Image Xfer Size   Domains


             0.5
                                     Highest Correlation to Render Time
            0.45

             0.4

            0.35

             0.3
                    Total Requests   Image Requests   Total Xfer Size   Image Xfer Size   Domains

http://mobile.httparchive.org/
HIGH PERFORMANCE – LESS REQUESTS

¡  Less Requests
   §  Bundling
      §  Maximum single request each for JS & CSS
          §    Single bundle more efficient use of bandwidth
          §    Blocks page while bundle downloaded
          §    Blocks page while bundle parsed
          §    Consider GMail approach to defer parsing (discussed later)
   §  Image Sprites
      §  Single PNG image
      §  Data URI
          §  Supported by: iPhone, Android, Opera
          §  Not supported by: IE, Nokia Series 40
      §  spriteme.org, css-sprit.es
   §  CSS3 for effects & ornaments (not images)
      §  Gradients, rounder corners, drop shadow, text shadow
   §  Avoid @font-face
      §  Size is between 10KB up to 4-5MB for Asian character sets
      §  Flash of un-styled text (FOUT) due to download & install
      §  6% of mobile pages use @font-face
   §  Aim at <= 1 requests
      §  We can do better than this….
HIGH PERFORMANCE – LESS REQUESTS

¡  Less Requests
  §  Inline scripts, css and images on first load
     §  Inline all resources, and send cookie
     §  Extract script, style and images into localStorage, update cookie
     §  Subsequent load check cookie
        §  If initial value
           §  no JavaScript or localStorage - return page with resources as external links (to
               utilize caching)
        §  If updated
           §  Output script to load resources from localStorage (at top of page)
     §  Bing
        §  1st request 54.9 KB
        §  2nd request 5.5 KB
HIGH PERFORMANCE – LESS REQUESTS

¡  Less Requests
  §  Application Cache
     §  <html manifest=“/manifest” >!
     §  Pros:
         §  Extremely fast
         §  Second page load 0 HTTP requests (for static content)
         §  Authoritative control of locally cached resources
     §  Cons:
         §    If file changes must update manifest file
         §    Makes page load asynchronous → second page load only
         §    Adaptive images → user cookie set on first load to determine image quality
         §    Double refresh issue → use updateready event on window.applicationCache and prompt user
         §    Atomic
         §    Impossible to version
         §    Buggy JS API
         §    Hard to invalidate
     §  Tip:
         §  Loads in order so CSS → PNG → JS
         §  Use NETWORK: * to make manifest “open”
HIGH PERFORMANCE – LESS REQUESTS

¡  Less Requests
  §  Application Cache
HIGH PERFORMANCE – LESS BY TES

   ¡  Less Bytes
            500                   Average Bytes per Page by Content Type (in KB)
            400

            300

            200

            100

                 0
                       Images         Scripts   Stylesheets   HTML       Other     Total


            16
            14
                                     Average Individual Response Size (in KB)
            12
            10
             8
             6
             4
             2
             0
                      JPEG            PNG          GIF        HTML        JS       CSS


http://mobile.httparchive.org/
HIGH PERFORMANCE – LESS BY TES

¡  Less Bytes
  §  Simple semantic HTML                                 Mobile Image Requests
     §  No divitis, classitis, iditis
     §  However:
        §  classes can improve css selector performance
        §  Ids can improve testability                        PNG
  §  Minify                                                   24%

     §  HTML, CSS, JS                                                           JPEG
  §  Optimize Images                                                            47%

     §  Use PNG instead of JPEG and GIF                      GIF
        §  GIFs for small images (i.e. <10x10 pixels)        29%
        §  JPEG for photographic-style images
     §  Maximize lossless compression
        §  JPEG: jpegtran, jpegoptim
                                                                         Other
        §  PNG: OptiPNG, PNGOUT                                          0%
        §  WebPageTest


                                                                     http://mobile.httparchive.org/
HIGH PERFORMANCE – LESS BY TES

¡  Less Bytes
  §  Adaptive Images
     §  Don’t scale images on the client
        §  Wastes bandwidth
        §  Requires device CPU
     §  Use @media, window.matchMedia(…), window.devicePixelRatio, etc
        §  -webkit-min-device-pixel-ratio (1 -> low res, 1.5 or 2 -> high res)
        §  For manifest file use capabilities cookie
     §  Server Scaling
        §  Multiple fixed breakpoints
          §  Allows for different designs (i.e. larger text on small images)
          §  Scale on demand in between major breakpoints
          §  Use CDN to “save” scaled images
HIGH PERFORMANCE – LESS BY TES

   ¡  Less Bytes
        §  Less JS
            §  Remove duplication
            §  Cost of parsing JavaScript about 1ms per 100KB
            §  Steve Souders – “every byte of JavaScript is 10x more expensive then
                everything else”
            §  Mini frameworks only
                §  Avoid → jQuery, Sencha, YUI, Dojo, etc
                   §  It takes between 1 .5s and 8s to parse and download jQuer y over 3G
                   §  jQuer yMobile wraps jQuer yUI with wraps jQuer y Core
                §  Use → XUI, Zepto, microJS, baseJS




http://www.slideshare.net/mobile/Gomez_Inc/optimizing-web-and-mobile-site-performance-using-page-speed
HIGH PERFORMANCE – LESS BY TES

¡  Less Bytes
  §  Compression
     §  More consistent data will compress better
        §    CSS key-value pairs in same order
        §    HTML attribute in same order
        §    Use lowercase (or consistent) casing wherever possible
        §    Use consistent quoting for HTML attributes (always single or always double)
        §    Minify JS, CSS and HTML
     §  Avoid gzip for image or other binary files
        §  These files are already compressed
HIGH PERFORMANCE – LESS BY TES

¡  Less Bytes
  §  Less Cookies
     §  Remove / reduce cookies
     §  Cookie Free Domain
     §  Server-Side Cookies (ID only)
            §  Store data on server side and only send unique ID
  §  HIJAX
     §  Smaller page request
     §  Could also use Hashbang
            §  Twitter accepts both https://twitter.com/#!/foo and https://twitter.com/foo
            §  Only works with JavaScript enabled
            §  Its an ugly hack and looks like one
     §  History API
            §  history.pushState() & ‘popstate’ event
     §  Don’t forget forward and backwards isn’t a page reload, it’s a page display
  §  Endless Scrolling Pattern
     §    Only download subset
     §    Less bytes
     §    Much more complexity
     §    Only worth while for very large data sets
     §    Recycle elements that are scrolled off screen
HIGH PERFORMANCE – BANDWIDTH

¡  Bandwidth Efficiency
  §  Fit request into single packet (if possible)
     §  Packet size ~1500 bytes
  §  Parallelize downloads
     §  Avoid blocking HTML parsing
       §  JS at the bottom
     §  Avoid delaying resource download
       §  Avoid @import
       §  document.write(…)
     §  Max requests per domain
       §  Domain sharding
         §  Adds DNS lookup → >6 request per domain
HIGH PERFORMANCE – BANDWIDTH

   ¡  Bandwidth Efficiency
       §  Defer JS requests
            §  Progressive enhance so delay in JS is never a problem
            §  defer & async
                §  download and parse not delayed
                §  tells browser there is no document.write(…)!
                §  async
                  §  executes after download
                  §  execution order not guaranteed
                §  defer
                  §  executes after parsing




http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/
HIGH PERFORMANCE – BANDWIDTH

¡  Bandwidth Efficiency
  §  Defer JS requests
     §  Downloading JS asynchronously
       §    XHR Eval
       §    XHR Injection
       §    Script in iframe
       §    Script DOM element
       §    document.write(…)
     §  Load scripts after onload to guarantee loaded asynchronous download
HIGH PERFORMANCE – BANDWIDTH

   ¡  Bandwidth Efficiency
        §  Eager loading
            §  Download in background and store in localStorage
            §  Mobile Web: <a class="eager" … />!
            §  Chromium: <link rel=“prerender” … />!
        §  Avoid bad requests (i.e. 404)
            §  7% mobile pages have (4xx) errors
        §  Avoid redirects
            §  73% mobile pages have (3xx) redirects
            §  If you can’t avoid cache
                 §  Language redirect for Accept-Language (see details on caching later)
                   §  Expires <= Date (to disable HTTP/1 .0 caches that don’t support Var y)
                   §  Cache-Control: max-age >= 1 year
                   §  Var y: Accept-Language




http://mobile.httparchive.org/
HIGH PERFORMANCE – BANDWIDTH

   ¡  Bandwidth Efficiency
        §  Dynamic Update




http://mobilehtml5.org/
HIGH PERFORMANCE – BANDWIDTH

¡  Bandwidth Efficiency
  §  Dynamic Update
     §  AJAX Polling
     §  Long Polling
     §  Server Side Events
     §  Web Sockets
  §  JSON vs HTML fragments
     §  Trade-off
        §  Less bytes on network
        §  Identical fixed network costs
        §  Much more complex JavaScript code that must work across multiple devices
          §  HTML fragment approach → simple identical JavaScript universally across the site
          §  JSON → custom JavaScript for ever y item of updatable content
HIGH PERFORMANCE – LESS LATENCY

¡  L e s s L a t e n c y
     §  Less server time
           §  Execute backend calls in parallel
           §  Avoid synchronization
                §    Threads
                §    DB (i.e. locking)
                      §    NoSQL
                      §    Eventual Consistency
           §  Use Futures to only block when absolutely required
           §  ETag → short circuit backend tasks
           §  Flush header while waiting for backend calls
                §    Allows CSS to be downloaded on client in parallel with backend calls
                §    HTTP/1.1
                      §    Trailer header allows addition of Content-Length, Last-Modifier and ETag with Transfer-Encoding: chunked
                §    Servlet 3.0 does NOT support this!!
     §  Under load scaling
           §  Avoid “too many” threads per request
                §    Threads should not be blocked waiting (i.e. IO / locks)
           §  No conversation state
                §    Must be managed across servers
                      §    Session replication
                      §    Sticky sessions
           §  Some state exists but not held on web server
                §    Decouple and isolates problem
                      §    Separation of concerns
                      §    Better encapsulation
                      §    Improves opportunity for graceful degradation
                §    Web Tier Persistence
                      §    Transient User Data (i.e. shopping basket, web UI preferences)
HIGH PERFORMANCE – LESS LATENCY

¡  Less Latency
  §  Minimize DNS lookups
     §  Mobile Web analytics request
        §  230ms DNS lookup
        §  76ms TCP + HTTP connection
        §  58ms server time
  §  Flush Early
     §  Check flush isn’t buffered
        §  Apache, Network (i.e. Netscaler), gzip
     §  Only works on HTTP/1.1 connections
     §  Uses Transfer-Encoding: chunked!
  §  Caching
     §  Make pages cacheable
        §  Avoid cookie or header driven content
          §  Except User- Agent, Accept-Language, Accept-Encoding
        §  Use path variable instead of query parameters
          §  Most proxy caches do not cache resources with quer y parameters
              §  i.e. only latest version of Squid fixes this
        §  Use fingerprinting to dynamically control caching
HIGH PERFORMANCE – LESS LATENCY

¡  L e s s L a t e n c y
     §  Caching
           §  Expires (HTTP/1.0)
                §    Date when resource is stale
           §  Cache-Control (HTTP/1.1)
                §    Overrides Expires header
                §    max-age - how long resource is fresh (in seconds)
                §    public, private – where item is cacheable
                §    no-store – never cache
                §    no-cache – always revalidate
                §    must-revalidate – revalidate if stale
                §    s-maxage, proxy-revalidate – proxy servers settings
           §  Vary (HTTP/1.1)
                §    Allows cached items to be varied by header
                §    If using disable HTTP/1.0 caches by Expires <= Date
           §  Tips
                §    Maximize freshness → 1 year
                      §    Android clears cache based on length of freshness → >10 years
           §  Last-Modified
                §    Last time resource modified
                §    If-Modified-Since – conditional GET
                §    If-Unmodified-Since – conditional PUT, DELETE
           §  ETag
                §    Ensure consistency across multiple web servers
                §    Unique identifier for specific resource version
                §    If-None-Match – conditional GET
                §    If-Match – conditional PUT, DELETE
                §    Favor semantic “week validator” over byte level “strong validator”
                §    Week Validator enables short-circuiting the server HTML generation
                §    Trailer: ETag supports Transfer-Encoding: chunked (not supported by Servlet 3.0)
           §  304 Not Modified
                §    Last-Modified
                §    ETag
HIGH PERFORMANCE – LESS LATENCY

   ¡  Less Latency
        §  Caching
            §  Not used enough
            45%
                                     Cache-Control: max-age (days)
            40%

            35%

            30%

            25%

            20%

            15%

            10%

             5%

             0%
                        None      t <= 0    0 < t <= 1   1 < t <= 30   30 < t <= 365   365 < t

http://mobile.httparchive.org/
HIGH PERFORMANCE – LESS LATENCY

   ¡  Less Latency
        §  Caching
            §  Browser
                §  Limited size
                §  Average mobile page size 550KB → < 7 pages to full reload

 OS (Device)
                                  Component
 Total
 Last-Modified
 ETag
 Survives Power Cycle
 Android 2.1 (Nexus One)
                          2MB
        2MB
    Yes
     Yes
          Yes
 Android 2.2 (Glaxay S)
                           4MB
        4MB
    Yes
     Yes
          Yes
 Android 2.3 (Nexus S)
                            4MB
        4MB
    Yes
     Yes
          Yes
 Safari, iOS 3.1.3 (1st-gen iPhone)
                0b
         0b
    No
      No
            No
 Safari, iOS 3.2 (iPad)
                           26KB
      282KB
   Yes
     Yes
           No
 Safari, iOS 4.0 (iPhone 3GS)
                     51KB
       1MB
    Yes
     Yes
           No
 Safari, iOS 4.0 (iPhone 4)
                      102KB
       2MB
    Yes
     Yes
           No
 webOS 1.4.1 (Palm Pre Plus)
                      1MB
          ?
    No
      No
           Yes
http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/
http://www.blaze.io/mobile/understanding-mobile-cache-sizes/
http://mobile.httparchive.org/trends.php#bytesTotal&reqTotal
HIGH PERFORMANCE – LESS LATENCY

¡  Less Latency
  §  Caching
     §  Reverse Proxy (i.e. ISP)
        §  Vary: Accept-Encoding
          §  many proxy caches do not detect Content-Encoding correctly
        §  Cookies
          §  Generally public caches won’t cache pages with cookies
          §  If they do cookies will be shared
     §  Edge / Gateway (i.e. CDN)
        §  Edge Side Include (ESI)
          §  Dynamic content assembly in cache
        §  Add icons:
          §  favicon.ico
          §  apple-touch-icon.png
          §  apple-touch-icon-precomposed.png
HIGH PERFORMANCE – LESS LATENCY

¡  Less Latency
     §  Offline Storage
          §    Single origin policy
          §    No freshness or cache eviction
          §    No versioning
          §    No request → very fast and works offline
          §    Manifest file
                  §    see earlier slides
          §    Web Storage
                  §    Local Storage (or Session Storage)
                  §    key/value storage of strings
                  §    Simple but no query language
                  §    No locks or transactions
                  §    No indexes or complex data structures
                  §    Slow, synchronous → blocking
                  §    Up to 5MB
                  §    Very fast
                  §    Synchronous
                  §    Only accessible from JavaScript
          §    Indexed DB
                  §    Flat-file DB
                  §    Hierarchical key/value persistence
                  §    Basic indexing
                  §    Fully asynchronous
                  §    Supports indexed filtering and lookup
                  §    DB level transactions & locking
                  §    Up to 5MB, then prompt user for more
                  §    Only accessible from JavaScript
          §    Web SQL Database
                  §    SQLite in browser
                  §    select, insert, update, delete, joins, inner selects, etc
                  §    Up to 5MB, then prompt user for more
                  §    Standard dropped by W3C
                  §    Slow
                  §    Only accessible from JavaScript
          §    File API
HIGH PERFORMANCE – LESS LATENCY

¡  Less Latency
  §  Radio Resource Control
     §  HEAD request every 2-3 seconds to keep cell connection live
     §  Drains battery and adds congestion so don’t poll forever
  §  Page Beacons (Analytics)
     §  Make asynchronous
        §  Inject 1x1.gif
     §  Separate domain
        §  Avoid site cookies infecting request
        §  Avoid analytics cookies infecting site
     §  304 response
     §  Maximize benefit
        §  Page flow
        §  Device capabilities
          §  @media / JS cookie
          §  User- A gent
        §  Connection Type
          §  navigator.connection.type!
               §  ETHERNET, WIFI, CELL_2G, CELL_3G, …!
        §  Carrier
          §  Massive’s Operator Identification Platform
HIGH PERFORMANCE – PAGE RENDER

¡  Faster Page Render
  §  Simple semantic DOM
    §  For every element (i.e. in Chrome)
          §  Node in DOM Tree
          §  RenderObject in RenderTree
  §  Efficient CSS selectors
    §    Avoid universal rules
    §    Don’t qualify id rules with tag names or classes
    §    Don’t qualify class rules with tag names
    §    Make rules as specific as possible
    §    Avoid descendant selectors (especially Tag or Universal)
    §    Apply rules at the highest level and allow inheritance
    §    Remove redundant qualifies
          §  ID selector with class or tag
          §  Class selector with tag
HIGH PERFORMANCE – PAGE RENDER

  ¡  Faster Page Render
       §  CSS in head
           §  External or inline style blocks in body can cause reflow or FOUC
           §  Allows page to render progressively
           §  External stylesheets block rendering until downloaded and parsed
       §  Use hardware accelerated CSS animations
           §  Gets GPUs directly involved with compositing
           §  Avoids slow video to system memory copies
           §  Less redraws of complete screen
               §  only compositing layer redraw and recomposition
       §  Use CSS instead of JS animation
       §  Specify image dimensions
           §  Avoids reflow after image downloaded
       §  Specify character set
           §  Avoids browser auto detecting (and making / correcting mistakes)
       §  Timers
           §  Lots of >1s timers
           §  Very few (i.e. one) <500ms timers

http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series-using.html
HIGH PERFORMANCE – INTERACTION

¡  Faster Interaction
   §  Defer JS parsing
      §  100ms per 1KB
      §  Make browser ignore code
             §  Comments
             §  None script element
      §  When needed use eval(…)!
   §  Avoid blocking single UI Thread
      §  Long-running JS = Unresponsive UI
      §  Asynchronous
             §  Use events
                §  Synthetic (via setTimeout in framework)
                §  Native
      §  Script Yeilding
             §  setTimeout(function() {…}, 50)!
                §  Different browsers have different timer resolutions / issues
                §  Short timeouts can significantly shorten battery life
             §  setImmediate(function() {…})!
                §  Add to back of UI Thread Queue (i.e. no timer)
                §  Not supported yet (only in IE 10)
   §  WebWorkers
      §    Asynchronous, doesn’t block UI Thread
      §    Data is serialized into and out of worker
      §    No access to DOM
      §    Separate execution environment
HIGH PERFORMANCE – INTERACTION

¡  Faster Interaction
  §  Touch delay
     §  Click event delayed between 300 and 500ms
     §  ontouchstart → ontouchend (with ontouchdrag within error margin)
  §  Event Handlers
     §  Event handlers on outer container
       §  Use event bubble
       §  Avoid lots of smaller event handlers
HIGH PERFORMANCE – INTERACTION

¡  Faster Interaction
  §  Touch
     §  Work directly with content
     §  Avoid button indirection
     §  Although gesture support currently limited
        §  Limited touch events
          §  touchstart, touchmove, touchend
  §  Fat fingers
     §  Fitt’s Law
        §  difficulty ∝ distance, size
     §  Large buttons
     §  Inactive margin
  §  Right first time
HIGH PERFORMANCE – PERCEPTION

¡  Improve Perception
  §  Flush early
  §  Visual feedback to user
    §  Button click changes color
  §  Image Interlacing
    §  Visible image after only 1/64 downloaded
    §  Adds ~15%
  §  Remove address bar
    §  While JavaScript is executing in background
    §  After onload
       §  window.scrollTo(0, 1);!
       §  If page height < window height then increase page height first to allow scroll
TOOLS – DEBUGGING

¡  Debugging
   §  Chrome Internals
      §    chrome://net-internals
      §    chrome://appcache-internals/
      §    chrome://profiler/
      §    For full list see chrome://chrome-urls/
      §    Works on Chrome for Android
   §  Firebug
      §  Desktop only
   §  BlackBerry Browser
      §  Remote debugging
      §  Smar tphone 7.0+
      §  PlayBook
   §  Web Inspector
      §  http://trac.webkit.org/wiki/WebInspector
   §  Wienre
      §  http://phonegap.github.com/weinre/
   §  DragonFly (for Opera Mobile)
   §  WebKit Remote Debugging
      §  http://www.webkit.org/blog/1620/webkit-remote-debugging/
   §  Adobe Shadow
      §  Synchronize desktop browser with multiple mobile browsers
      §  http://labs.adobe.com/technologies/shadow/
TOOLS – PERFORMANCE

¡    Performance / Analysis
       §    Chrome Inspector
              §    JS & CSS Profiler
       §    PageSpeed
              §    Chrome Inspector
              §    Firebug
       §    YSlow
              §    Chrome Inspector
              §    Firebug
       §    Mobile Perf Bookmarklets
              §    YSlow and other tools
              §    http://stevesouders.com/mobileperf/mobileperfbkm.php
       §    PCAP Web Performance Analyzer
              §    http://pcapperf.appspot.com/
              §    Analyse packets → Waterfall & WebPageTest
       §    Shark for Root
              §    Android packet sniffer
              §    Works with 3G
              §    Analyse results (PCAP file) with pcapperf
       §    Speed Tracer
              §    Chrome Inspector Plugin
              §    Analyses all page interaction (CSS & JS)
       §    3PMobile
              §    On device browser
              §    Network Waterfall
              §    Browser Event (i.e. image loading time, CSS processing time)
       §    dynaTrace
              §    JS performance analyser
              §    http://ajax.dynatrace.com/
       §    Loadtimer
              §    Tests time for full load of multiple URLs
              §    http://www.stevesouders.com/blog/2011/12/01/loadtimer-a-mobile-test-harness/
       §    WebPageTest
              §    Waterfall of network traffic
              §    Timing of page load event adds noise
TOOLS – EMULATORS

¡  Emulators
   §  www.mobilexweb.com/emulators
¡  Remote Labs
   §  DeviceAnywhere (bought by WebPageTest)
      §  deviceanywhere.com
   §  PerfectoMobile
      §  perfectomobile.com
   §  WebPageTest
   §  Samsung
      §  Free hosting of Samsung devices
      §  http://developer.samsung.com/remoteTestLab.do
   §  Nokia
      §  Free hosting of Nokia devices
¡  Experimental
   §  Cuzillion
      §  Build up different types of page
          §  internal / external CSS
          §  internal / external JS
          §  images
      §  Good for testing and learning about new devices / browsers
      §  http://stevesouders.com/cuzillion/

Contenu connexe

Tendances

Happy Browser, Happy User! NY Web Performance Meetup 9/20/19
Happy Browser, Happy User! NY Web Performance Meetup 9/20/19Happy Browser, Happy User! NY Web Performance Meetup 9/20/19
Happy Browser, Happy User! NY Web Performance Meetup 9/20/19Katie Sylor-Miller
 
Imagesandvideo stockholm webmeetup
Imagesandvideo stockholm webmeetupImagesandvideo stockholm webmeetup
Imagesandvideo stockholm webmeetupDoug Sillars
 
Shopzilla - Performance By Design
Shopzilla - Performance By DesignShopzilla - Performance By Design
Shopzilla - Performance By DesignTim Morrow
 
Image-ine That: Image Optimization for Conversion Maximization
Image-ine That: Image Optimization for Conversion MaximizationImage-ine That: Image Optimization for Conversion Maximization
Image-ine That: Image Optimization for Conversion MaximizationYottaa
 
10+апреля+лучшие+практики+и+инновации+вадим+береговский+akamai
10+апреля+лучшие+практики+и+инновации+вадим+береговский+akamai10+апреля+лучшие+практики+и+инновации+вадим+береговский+akamai
10+апреля+лучшие+практики+и+инновации+вадим+береговский+akamaielenae00
 
Raiders of the Fast Start: Frontend Performance Archaeology - Performance.now...
Raiders of the Fast Start: Frontend Performance Archaeology - Performance.now...Raiders of the Fast Start: Frontend Performance Archaeology - Performance.now...
Raiders of the Fast Start: Frontend Performance Archaeology - Performance.now...Katie Sylor-Miller
 
7 Habits of Exceptional Performance
7 Habits of Exceptional Performance7 Habits of Exceptional Performance
7 Habits of Exceptional PerformanceNicole Sullivan
 
Extreme Web Performance for Mobile Devices - Velocity NY
Extreme Web Performance for Mobile Devices - Velocity NYExtreme Web Performance for Mobile Devices - Velocity NY
Extreme Web Performance for Mobile Devices - Velocity NYMaximiliano Firtman
 
Inside Picnik: How We Built Picnik (and What We Learned Along the Way)
Inside Picnik: How We Built Picnik (and What We Learned Along the Way)Inside Picnik: How We Built Picnik (and What We Learned Along the Way)
Inside Picnik: How We Built Picnik (and What We Learned Along the Way)jjhuff
 
Performance Implications of Mobile Design (Perf Audience Edition)
Performance Implications of Mobile Design (Perf Audience Edition)Performance Implications of Mobile Design (Perf Audience Edition)
Performance Implications of Mobile Design (Perf Audience Edition)Guy Podjarny
 
Step by Step Mobile Optimization
Step by Step Mobile OptimizationStep by Step Mobile Optimization
Step by Step Mobile OptimizationGuy Podjarny
 
Recipes for the Perfect PI v2.0
Recipes for the Perfect PI v2.0Recipes for the Perfect PI v2.0
Recipes for the Perfect PI v2.0Sascha Wenninger
 
Velocity NY 2013 - From Slow to Fast: Improving Performance on Intuit Website...
Velocity NY 2013 - From Slow to Fast: Improving Performance on Intuit Website...Velocity NY 2013 - From Slow to Fast: Improving Performance on Intuit Website...
Velocity NY 2013 - From Slow to Fast: Improving Performance on Intuit Website...Jay Hung
 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Timothy Fisher
 
Web Performance & You - HighEdWeb Arkansas Version
Web Performance & You - HighEdWeb Arkansas VersionWeb Performance & You - HighEdWeb Arkansas Version
Web Performance & You - HighEdWeb Arkansas VersionDave Olsen
 
Mot cph when its just too slow
Mot cph when its just too slowMot cph when its just too slow
Mot cph when its just too slowDoug Sillars
 
A Beard, An App, A Blender
A Beard, An App, A BlenderA Beard, An App, A Blender
A Beard, An App, A Blenderedm00se
 
Its timetostopstalling sw_mobile_bristol
Its timetostopstalling sw_mobile_bristolIts timetostopstalling sw_mobile_bristol
Its timetostopstalling sw_mobile_bristolDoug Sillars
 
IBM Connect 2016 - AD1548 - Building Responsive XPages Applications
IBM Connect 2016 - AD1548 - Building Responsive XPages ApplicationsIBM Connect 2016 - AD1548 - Building Responsive XPages Applications
IBM Connect 2016 - AD1548 - Building Responsive XPages Applicationsbeglee
 

Tendances (20)

Happy Browser, Happy User! NY Web Performance Meetup 9/20/19
Happy Browser, Happy User! NY Web Performance Meetup 9/20/19Happy Browser, Happy User! NY Web Performance Meetup 9/20/19
Happy Browser, Happy User! NY Web Performance Meetup 9/20/19
 
Imagesandvideo stockholm webmeetup
Imagesandvideo stockholm webmeetupImagesandvideo stockholm webmeetup
Imagesandvideo stockholm webmeetup
 
Shopzilla - Performance By Design
Shopzilla - Performance By DesignShopzilla - Performance By Design
Shopzilla - Performance By Design
 
Image-ine That: Image Optimization for Conversion Maximization
Image-ine That: Image Optimization for Conversion MaximizationImage-ine That: Image Optimization for Conversion Maximization
Image-ine That: Image Optimization for Conversion Maximization
 
10+апреля+лучшие+практики+и+инновации+вадим+береговский+akamai
10+апреля+лучшие+практики+и+инновации+вадим+береговский+akamai10+апреля+лучшие+практики+и+инновации+вадим+береговский+akamai
10+апреля+лучшие+практики+и+инновации+вадим+береговский+akamai
 
Raiders of the Fast Start: Frontend Performance Archaeology - Performance.now...
Raiders of the Fast Start: Frontend Performance Archaeology - Performance.now...Raiders of the Fast Start: Frontend Performance Archaeology - Performance.now...
Raiders of the Fast Start: Frontend Performance Archaeology - Performance.now...
 
7 Habits of Exceptional Performance
7 Habits of Exceptional Performance7 Habits of Exceptional Performance
7 Habits of Exceptional Performance
 
Extreme Web Performance for Mobile Devices - Velocity NY
Extreme Web Performance for Mobile Devices - Velocity NYExtreme Web Performance for Mobile Devices - Velocity NY
Extreme Web Performance for Mobile Devices - Velocity NY
 
Inside Picnik: How We Built Picnik (and What We Learned Along the Way)
Inside Picnik: How We Built Picnik (and What We Learned Along the Way)Inside Picnik: How We Built Picnik (and What We Learned Along the Way)
Inside Picnik: How We Built Picnik (and What We Learned Along the Way)
 
Performance Implications of Mobile Design (Perf Audience Edition)
Performance Implications of Mobile Design (Perf Audience Edition)Performance Implications of Mobile Design (Perf Audience Edition)
Performance Implications of Mobile Design (Perf Audience Edition)
 
Step by Step Mobile Optimization
Step by Step Mobile OptimizationStep by Step Mobile Optimization
Step by Step Mobile Optimization
 
Recipes for the Perfect PI v2.0
Recipes for the Perfect PI v2.0Recipes for the Perfect PI v2.0
Recipes for the Perfect PI v2.0
 
After YSlow "A"
After YSlow "A"After YSlow "A"
After YSlow "A"
 
Velocity NY 2013 - From Slow to Fast: Improving Performance on Intuit Website...
Velocity NY 2013 - From Slow to Fast: Improving Performance on Intuit Website...Velocity NY 2013 - From Slow to Fast: Improving Performance on Intuit Website...
Velocity NY 2013 - From Slow to Fast: Improving Performance on Intuit Website...
 
Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011Developing High Performance Web Apps - CodeMash 2011
Developing High Performance Web Apps - CodeMash 2011
 
Web Performance & You - HighEdWeb Arkansas Version
Web Performance & You - HighEdWeb Arkansas VersionWeb Performance & You - HighEdWeb Arkansas Version
Web Performance & You - HighEdWeb Arkansas Version
 
Mot cph when its just too slow
Mot cph when its just too slowMot cph when its just too slow
Mot cph when its just too slow
 
A Beard, An App, A Blender
A Beard, An App, A BlenderA Beard, An App, A Blender
A Beard, An App, A Blender
 
Its timetostopstalling sw_mobile_bristol
Its timetostopstalling sw_mobile_bristolIts timetostopstalling sw_mobile_bristol
Its timetostopstalling sw_mobile_bristol
 
IBM Connect 2016 - AD1548 - Building Responsive XPages Applications
IBM Connect 2016 - AD1548 - Building Responsive XPages ApplicationsIBM Connect 2016 - AD1548 - Building Responsive XPages Applications
IBM Connect 2016 - AD1548 - Building Responsive XPages Applications
 

Similaire à Mobile Web Best Practices

Mobile Web & HTML5 Performance Optimization
Mobile Web & HTML5 Performance OptimizationMobile Web & HTML5 Performance Optimization
Mobile Web & HTML5 Performance OptimizationMaximiliano Firtman
 
Developing the MIT Mobile Web
Developing the MIT Mobile WebDeveloping the MIT Mobile Web
Developing the MIT Mobile Webshu beta
 
Maximiliano Firtman - Разработка приложений с помощью PhoneGap
Maximiliano Firtman - Разработка приложений с помощью PhoneGap Maximiliano Firtman - Разработка приложений с помощью PhoneGap
Maximiliano Firtman - Разработка приложений с помощью PhoneGap .toster
 
Best practices for delivering quality web experiences
Best practices for delivering quality web experiencesBest practices for delivering quality web experiences
Best practices for delivering quality web experiencesBen Mantooth
 
The mobile browser world
The mobile browser worldThe mobile browser world
The mobile browser worldPeter-Paul Koch
 
Mobile Web High Performance
Mobile Web High PerformanceMobile Web High Performance
Mobile Web High PerformanceAmjad Rafique
 
Extreme Web Performance for Mobile Devices - Velocity Barcelona 2014
Extreme Web Performance for Mobile Devices - Velocity Barcelona 2014Extreme Web Performance for Mobile Devices - Velocity Barcelona 2014
Extreme Web Performance for Mobile Devices - Velocity Barcelona 2014Maximiliano Firtman
 
Leverage web technology in a mobile world
Leverage web technology in a mobile worldLeverage web technology in a mobile world
Leverage web technology in a mobile worldDieter Blomme
 
My Web Performance Dirty Secrets
My Web Performance Dirty SecretsMy Web Performance Dirty Secrets
My Web Performance Dirty SecretsFred Beringer
 
Mobile for PHP developers
Mobile for PHP developersMobile for PHP developers
Mobile for PHP developersIvo Jansch
 
The mobile browser world
The mobile browser worldThe mobile browser world
The mobile browser worldPeter-Paul Koch
 
Android platform
Android platformAndroid platform
Android platformmaya_slides
 
Widgets in theory and in practice
Widgets in theory and in practiceWidgets in theory and in practice
Widgets in theory and in practiceourmaninjapan
 
Ugly truths about html5 moosecon - robert virkus - 2013-03-07
Ugly truths about html5   moosecon - robert virkus - 2013-03-07Ugly truths about html5   moosecon - robert virkus - 2013-03-07
Ugly truths about html5 moosecon - robert virkus - 2013-03-07Enough Software
 
Siruna session at Drupalcon Paris 2009
Siruna session at Drupalcon Paris 2009Siruna session at Drupalcon Paris 2009
Siruna session at Drupalcon Paris 2009Tom Deryckere
 
Drupalcamp New York 2009
Drupalcamp New York 2009Drupalcamp New York 2009
Drupalcamp New York 2009Tom Deryckere
 
Unravelling Mobile Web Performance
Unravelling Mobile Web PerformanceUnravelling Mobile Web Performance
Unravelling Mobile Web PerformanceGuy Podjarny
 
Performance Testing in a Mobile World
Performance Testing in a Mobile WorldPerformance Testing in a Mobile World
Performance Testing in a Mobile Worldstuartmoncrieff
 

Similaire à Mobile Web Best Practices (20)

Mobile Web & HTML5 Performance Optimization
Mobile Web & HTML5 Performance OptimizationMobile Web & HTML5 Performance Optimization
Mobile Web & HTML5 Performance Optimization
 
Developing the MIT Mobile Web
Developing the MIT Mobile WebDeveloping the MIT Mobile Web
Developing the MIT Mobile Web
 
Mobile Web High Performance
Mobile Web High PerformanceMobile Web High Performance
Mobile Web High Performance
 
PhoneGap mobile development
PhoneGap mobile developmentPhoneGap mobile development
PhoneGap mobile development
 
Maximiliano Firtman - Разработка приложений с помощью PhoneGap
Maximiliano Firtman - Разработка приложений с помощью PhoneGap Maximiliano Firtman - Разработка приложений с помощью PhoneGap
Maximiliano Firtman - Разработка приложений с помощью PhoneGap
 
Best practices for delivering quality web experiences
Best practices for delivering quality web experiencesBest practices for delivering quality web experiences
Best practices for delivering quality web experiences
 
The mobile browser world
The mobile browser worldThe mobile browser world
The mobile browser world
 
Mobile Web High Performance
Mobile Web High PerformanceMobile Web High Performance
Mobile Web High Performance
 
Extreme Web Performance for Mobile Devices - Velocity Barcelona 2014
Extreme Web Performance for Mobile Devices - Velocity Barcelona 2014Extreme Web Performance for Mobile Devices - Velocity Barcelona 2014
Extreme Web Performance for Mobile Devices - Velocity Barcelona 2014
 
Leverage web technology in a mobile world
Leverage web technology in a mobile worldLeverage web technology in a mobile world
Leverage web technology in a mobile world
 
My Web Performance Dirty Secrets
My Web Performance Dirty SecretsMy Web Performance Dirty Secrets
My Web Performance Dirty Secrets
 
Mobile for PHP developers
Mobile for PHP developersMobile for PHP developers
Mobile for PHP developers
 
The mobile browser world
The mobile browser worldThe mobile browser world
The mobile browser world
 
Android platform
Android platformAndroid platform
Android platform
 
Widgets in theory and in practice
Widgets in theory and in practiceWidgets in theory and in practice
Widgets in theory and in practice
 
Ugly truths about html5 moosecon - robert virkus - 2013-03-07
Ugly truths about html5   moosecon - robert virkus - 2013-03-07Ugly truths about html5   moosecon - robert virkus - 2013-03-07
Ugly truths about html5 moosecon - robert virkus - 2013-03-07
 
Siruna session at Drupalcon Paris 2009
Siruna session at Drupalcon Paris 2009Siruna session at Drupalcon Paris 2009
Siruna session at Drupalcon Paris 2009
 
Drupalcamp New York 2009
Drupalcamp New York 2009Drupalcamp New York 2009
Drupalcamp New York 2009
 
Unravelling Mobile Web Performance
Unravelling Mobile Web PerformanceUnravelling Mobile Web Performance
Unravelling Mobile Web Performance
 
Performance Testing in a Mobile World
Performance Testing in a Mobile WorldPerformance Testing in a Mobile World
Performance Testing in a Mobile World
 

Dernier

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Dernier (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

Mobile Web Best Practices

  • 1. MOBILE WEB BEST PRACTICES http://about.me/jamesdbloom http://blog.jamesdbloom.com JamesDBloom
  • 2. PERCENTAGE OF MOBILE WEB 50% 45% 40% 35% 30% 25% 20% 15% 10% 5% 0% http://www.tecmark.co.uk/wp-content/uploads/2011/08/Mobile-and-UK-Web-Traffic-August-2011.pdf
  • 3. WHAT I’M TALKING ABOUT ¡  The Problem §  What’s different and hard about mobile ¡  The Solution §  Adaptive Techniques §  Mobile First §  Avoid JavaScript §  Device Detection §  Adaptive Design §  Progressive Enhancement §  High Performance §  Network §  Less Request §  Less Bytes §  Bandwidth Efficiency §  Less Latency §  Sof tware §  Faster Page Rendering §  Faster Interaction §  User §  Faster Interaction §  Improve Perception ¡  Tools §  Debugging §  Performance §  Emulators
  • 4. WHAT’S MOBILE – THE PROBLEM ¡  Network §  Different types of network: §  GSM, GPRS, WCDMA, UMTS, EDGE, HSPA, UMTS, LTE, WiMAX §  High latencies §  300ms to 1000ms §  High packet loss §  From 0.1% to >20% §  Each time triggers TCP Slow Start again §  Radio Resource Control (RRC) §  Adds 1.5s to 2s to initiate connection §  Total Connection Time §  RRC + DNS + TCP 3-way handshake + TCP slow start + HTTP Request §  SSL adds even more §  Bandwidth §  3G §  Download: ~1Mbps Upload: ~0.5 Mbps §  Broadband §  Download: ~9Mbps Upload: ~2Mbps
  • 5. WHAT’S MOBILE – THE PROBLEM ¡  Device §  Rapidly changing, widely diverse hardware §  “2500 different devices on Facebook per month” - Tobie Langel 7000 SunSpider JS Benchmark (in ms) for some of the devices released in the last year 6000 5000 4000 3000 2000 1000 0 http://www.anandtech.com/show/5584/htcs-new-strategy-the-htc-one
  • 6. WHAT’S MOBILE – THE PROBLEM ¡  Device §  Slow CPU §  10x slower then desktop §  JavaScript that runs for 100ms on desktop will take ~1s on mobile §  Low memory §  Mobile RAM in MB §  Desktop RAM in GB §  Small screen §  Navigation §  Touch §  Gestures: Tap, Double Tap, Drag, Flick, Pinch, Spread, Press, Press & Tap, Press & Drag, Rotate, … §  More direct interaction §  But different on each device §  Focus §  Pointer Google Tech Talk - November 10, 2011 - Guy Podjarny
  • 7. WHAT’S MOBILE – THE PROBLEM ¡  Software §  Rapidly changing, widely diverse browsers and operating systems No Browser Creator No Browser Creator 1 Android Browser Google 21 Obigo Browser Obigo AB 2 Apollo Team Apollo 22 Opera Mini Opera Software 3 BlackBerry Browser Research in Motion 23 Opera Mobile Opera Software 4 Blazer Palm 24 Palm HP 5 Bada Samsung 25 Pixo Sun Microsystems 6 Chrome for Android Google 26 PlayStation Portable Sony 7 Classilla Cameron Kaiser 27 Polaris Browser Infraware 8 Deepfish Microsoft 28 Safari Apple 9 Dolphin Browser MoboTap 29 Symbian / S60 Nokia 30 Skweezer 10 Firefox for mobile Mozilla Foundation 31 Skyfire Skyfire Labs 11 ibisBrowser ibis 32 Skyfire Mobile Browser Skyfire 12 Internet Explorer Mobile Microsoft 33 Steel 13 Iris Browser Torch Mobile 34 Teashark 14 JOCA InteracT!V 35 Tristit 15 Kindle Basic Web Amazon.com 36 UC Browser UC Mobile 16 MIB Motorola 17 Minimo Mozilla Foundation 37 uZard Web Logicplant 18 Myriad / Openwave Myriad Group 38 Vision Mobile Browser Novarra 19 NetFront ACCESS 39 WebOS Browser Palm 20 Nokia Series 40 Browser Nokia 40 WinWAP Winwap Technologies
  • 8. WHAT’S MOBILE – THE PROBLEM ¡  Sof tware §  Changing rapidly §  Different navigation method §  Proxied vs Direct §  Proxied – Opera Mini, Kindle Fire §  Direct – all others §  HTTP vs SPDY §  SPDY – Kindle Fire, Chrome for Android §  HTTP – all others §  Process models §  Multi Process – Chrome for Android §  Single Process - all others §  Small Cache §  2-4MB §  Connections §  Max Total §  Max per host §  Pipelined §  Multiple requests over a single socket without waiting for a response §  Problems with proxies and head-of-line blocking
  • 9. WHAT’S MOBILE – THE PROBLEM ¡  Users §  Distracted §  i.e. walking down the street §  Shorter interactions §  i.e. waiting for a bus §  Touch §  Fat fingers §  Gestures (are they all intuitive?) §  Targeted tasks §  i.e. what are the local restaurants? §  Expectations §  Web that “pretends” to be app is likely to disappoint §  85% - “customers expect to be able to shop on their phones and want the experience to be as good or better than on a computer” http://www.nytimes.com/2011/04/18/technology/18mobile.html?_r=3
  • 10. MOBILE FIRST ¡  Mobile first §  Start simple and build up §  Test for presence (and function) of all APIs §  If it exists it may not work correctly §  Everything should fallback §  local storage → local variable → no storage §  push & pop state → hash bang fall → page refresh §  auto refresh → manual refresh button §  Avoid native events → use synthetic events §  minimizes difference between browsers ¡  Forget pixel perfect §  Fluid grids §  Adaptive design
  • 11. AVOID JAVASCRIPT ¡  Avoid JS → Middle Tier §  Why are we re-implementing the browser? §  Maximize stability across devices, even unknown devices §  Ensure site works without JS §  You control execution environment §  More reliable §  Easier to test §  Limit device dependent code §  Easier to automate tests §  Simplify browser interaction helps Selenium §  More code covered by Java unit tests §  Easier to optimize §  Scale out / up §  Easier to diagnose issues §  Well understood §  Better tools
  • 12. ADAPT – DEVICE DETECTION ¡  Breakpoints §  Major breakpoint on server §  Chose fixed high level breakpoints §  Mobile §  Tablet §  Desktop §  TV §  Avoid serving desktop site on mobile width §  Too heavy §  Too slow to download §  Too slow to render §  Not optimized correctly §  Adapt §  Content §  Layout §  Features §  Page weight §  Caching §  Vary: User-Agent!
  • 13. ADAPT – DEVICE DETECTION ¡  Breakpoints §  How to select major breakpoint §  Headers §  User-Agent §  Accept §  x-wap-profile / Profile §  UAProfile with device capabilities and preferences (W3C Ubiquitous Web Applications Working Group – closed July 2010) §  OperaMini §  Device Libraries §  WURFL §  Open Source §  Slightly limited information §  Based on UAProfile §  DeviceAtlas §  Started by Ericsson, Google, GSM Association, Microsoft, Nokia, Samsung, T-Mobile, Telecom, Telecom Italia, Visa and Vodafone §  51Degrees §  Build into ASP.NET and MVC.NET §  DetectRight §  Custom DB §  Augment existing device library §  Log capabilities (i.e. cookie / analytics / JS) §  Tools §  Spring Mobile §  WURFL §  Apache Mobile Filter §  WURFL §  51Degrees §  DetectRight
  • 14. ADAPT – ADAPTIVE DESIGN ¡  Breakpoints §  Minor breakpoint on client §  @media §  Screen size, resolution & pixel density §  Fluid grids, dif ferent columns, adapt image size (see earlier slide) §  navigator.connection.type! §  ETHERNET, WIFI, CELL_2G, CELL_3G, …! §  Send to server §  Cookie §  JS §  Landscape vs portrait §  Consider width of screen not width of viewport §  Test for presence (and function) of all APIs §  If it exists it may not work correctly §  Everything should fallback §  local storage → local variable → no storage §  push & pop state → hash bang fall → page refresh §  auto refresh → manual refresh button §  Indicate it’s a mobile website
  • 15. ADAPT – PROGRESSIVE ENHANCEMENT ¡  Progressive Enhancement §  Test for presence (and function) of all APIs §  If it exists it may not work correctly HTML5 §  Everything should fallback §  local storage → local variable → no storage §  push & pop state → hash bang fall → page AJAX / HIJAX refresh §  auto refresh → manual refresh button §  HTML5 CSS Extensions §  Not fully supported §  mobilehtml5.org Basic JavaScript §  www.modernizr.com §  caniuse.com §  www.browserscope.org Advanced CSS §  www.quirksmode.org §  PolyFills Simple CSS §  Add weight §  Better to except not supported and degrade HTML
  • 16. HIGH PERFORMANCE – WHY? ¡  47% expect page load < 2s ¡  40% abandon sites with page load > 3s ¡  +1s → -7% conversion rate ¡  if $100,000 per day, +1s → $2.5 million lost sales ever y year ¡  Bing §  +1s → -4% revenue ¡  Google §  0.4s to 0.9s → -25% searches (-$2.5 billion revenue) ¡  Firefox §  -2.2s download page → +15% downloads (+1.7 million extra / year) ¡  Shopzilla §  -5s → +7-12% revenue, -50% hardware cost ¡  Wallmart & Amazon §  every -100ms → +1% revenue http://blog.kissmetrics.com/loading-time/ http://blog.mozilla.com/metrics/category/website-optimization/ http://radar.oreilly.com/2009/07/velocity-making-your-site-fast.html http://www.webperformancetoday.com/2012/02/28/4-awesome-slides-showing-how-page-speed-correlates-to-business-metrics-at-walmart-com/
  • 17. HIGH PERFORMANCE – LESS REQUESTS ¡  Less Requests 0.5 Highest Correlation to Load Time 0.45 0.4 0.35 Total Requests Image Requests Total Xfer Size Image Xfer Size Domains 0.5 Highest Correlation to Render Time 0.45 0.4 0.35 0.3 Total Requests Image Requests Total Xfer Size Image Xfer Size Domains http://mobile.httparchive.org/
  • 18. HIGH PERFORMANCE – LESS REQUESTS ¡  Less Requests §  Bundling §  Maximum single request each for JS & CSS §  Single bundle more efficient use of bandwidth §  Blocks page while bundle downloaded §  Blocks page while bundle parsed §  Consider GMail approach to defer parsing (discussed later) §  Image Sprites §  Single PNG image §  Data URI §  Supported by: iPhone, Android, Opera §  Not supported by: IE, Nokia Series 40 §  spriteme.org, css-sprit.es §  CSS3 for effects & ornaments (not images) §  Gradients, rounder corners, drop shadow, text shadow §  Avoid @font-face §  Size is between 10KB up to 4-5MB for Asian character sets §  Flash of un-styled text (FOUT) due to download & install §  6% of mobile pages use @font-face §  Aim at <= 1 requests §  We can do better than this….
  • 19. HIGH PERFORMANCE – LESS REQUESTS ¡  Less Requests §  Inline scripts, css and images on first load §  Inline all resources, and send cookie §  Extract script, style and images into localStorage, update cookie §  Subsequent load check cookie §  If initial value §  no JavaScript or localStorage - return page with resources as external links (to utilize caching) §  If updated §  Output script to load resources from localStorage (at top of page) §  Bing §  1st request 54.9 KB §  2nd request 5.5 KB
  • 20. HIGH PERFORMANCE – LESS REQUESTS ¡  Less Requests §  Application Cache §  <html manifest=“/manifest” >! §  Pros: §  Extremely fast §  Second page load 0 HTTP requests (for static content) §  Authoritative control of locally cached resources §  Cons: §  If file changes must update manifest file §  Makes page load asynchronous → second page load only §  Adaptive images → user cookie set on first load to determine image quality §  Double refresh issue → use updateready event on window.applicationCache and prompt user §  Atomic §  Impossible to version §  Buggy JS API §  Hard to invalidate §  Tip: §  Loads in order so CSS → PNG → JS §  Use NETWORK: * to make manifest “open”
  • 21. HIGH PERFORMANCE – LESS REQUESTS ¡  Less Requests §  Application Cache
  • 22. HIGH PERFORMANCE – LESS BY TES ¡  Less Bytes 500 Average Bytes per Page by Content Type (in KB) 400 300 200 100 0 Images Scripts Stylesheets HTML Other Total 16 14 Average Individual Response Size (in KB) 12 10 8 6 4 2 0 JPEG PNG GIF HTML JS CSS http://mobile.httparchive.org/
  • 23. HIGH PERFORMANCE – LESS BY TES ¡  Less Bytes §  Simple semantic HTML Mobile Image Requests §  No divitis, classitis, iditis §  However: §  classes can improve css selector performance §  Ids can improve testability PNG §  Minify 24% §  HTML, CSS, JS JPEG §  Optimize Images 47% §  Use PNG instead of JPEG and GIF GIF §  GIFs for small images (i.e. <10x10 pixels) 29% §  JPEG for photographic-style images §  Maximize lossless compression §  JPEG: jpegtran, jpegoptim Other §  PNG: OptiPNG, PNGOUT 0% §  WebPageTest http://mobile.httparchive.org/
  • 24. HIGH PERFORMANCE – LESS BY TES ¡  Less Bytes §  Adaptive Images §  Don’t scale images on the client §  Wastes bandwidth §  Requires device CPU §  Use @media, window.matchMedia(…), window.devicePixelRatio, etc §  -webkit-min-device-pixel-ratio (1 -> low res, 1.5 or 2 -> high res) §  For manifest file use capabilities cookie §  Server Scaling §  Multiple fixed breakpoints §  Allows for different designs (i.e. larger text on small images) §  Scale on demand in between major breakpoints §  Use CDN to “save” scaled images
  • 25. HIGH PERFORMANCE – LESS BY TES ¡  Less Bytes §  Less JS §  Remove duplication §  Cost of parsing JavaScript about 1ms per 100KB §  Steve Souders – “every byte of JavaScript is 10x more expensive then everything else” §  Mini frameworks only §  Avoid → jQuery, Sencha, YUI, Dojo, etc §  It takes between 1 .5s and 8s to parse and download jQuer y over 3G §  jQuer yMobile wraps jQuer yUI with wraps jQuer y Core §  Use → XUI, Zepto, microJS, baseJS http://www.slideshare.net/mobile/Gomez_Inc/optimizing-web-and-mobile-site-performance-using-page-speed
  • 26. HIGH PERFORMANCE – LESS BY TES ¡  Less Bytes §  Compression §  More consistent data will compress better §  CSS key-value pairs in same order §  HTML attribute in same order §  Use lowercase (or consistent) casing wherever possible §  Use consistent quoting for HTML attributes (always single or always double) §  Minify JS, CSS and HTML §  Avoid gzip for image or other binary files §  These files are already compressed
  • 27. HIGH PERFORMANCE – LESS BY TES ¡  Less Bytes §  Less Cookies §  Remove / reduce cookies §  Cookie Free Domain §  Server-Side Cookies (ID only) §  Store data on server side and only send unique ID §  HIJAX §  Smaller page request §  Could also use Hashbang §  Twitter accepts both https://twitter.com/#!/foo and https://twitter.com/foo §  Only works with JavaScript enabled §  Its an ugly hack and looks like one §  History API §  history.pushState() & ‘popstate’ event §  Don’t forget forward and backwards isn’t a page reload, it’s a page display §  Endless Scrolling Pattern §  Only download subset §  Less bytes §  Much more complexity §  Only worth while for very large data sets §  Recycle elements that are scrolled off screen
  • 28. HIGH PERFORMANCE – BANDWIDTH ¡  Bandwidth Efficiency §  Fit request into single packet (if possible) §  Packet size ~1500 bytes §  Parallelize downloads §  Avoid blocking HTML parsing §  JS at the bottom §  Avoid delaying resource download §  Avoid @import §  document.write(…) §  Max requests per domain §  Domain sharding §  Adds DNS lookup → >6 request per domain
  • 29. HIGH PERFORMANCE – BANDWIDTH ¡  Bandwidth Efficiency §  Defer JS requests §  Progressive enhance so delay in JS is never a problem §  defer & async §  download and parse not delayed §  tells browser there is no document.write(…)! §  async §  executes after download §  execution order not guaranteed §  defer §  executes after parsing http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/
  • 30. HIGH PERFORMANCE – BANDWIDTH ¡  Bandwidth Efficiency §  Defer JS requests §  Downloading JS asynchronously §  XHR Eval §  XHR Injection §  Script in iframe §  Script DOM element §  document.write(…) §  Load scripts after onload to guarantee loaded asynchronous download
  • 31. HIGH PERFORMANCE – BANDWIDTH ¡  Bandwidth Efficiency §  Eager loading §  Download in background and store in localStorage §  Mobile Web: <a class="eager" … />! §  Chromium: <link rel=“prerender” … />! §  Avoid bad requests (i.e. 404) §  7% mobile pages have (4xx) errors §  Avoid redirects §  73% mobile pages have (3xx) redirects §  If you can’t avoid cache §  Language redirect for Accept-Language (see details on caching later) §  Expires <= Date (to disable HTTP/1 .0 caches that don’t support Var y) §  Cache-Control: max-age >= 1 year §  Var y: Accept-Language http://mobile.httparchive.org/
  • 32. HIGH PERFORMANCE – BANDWIDTH ¡  Bandwidth Efficiency §  Dynamic Update http://mobilehtml5.org/
  • 33. HIGH PERFORMANCE – BANDWIDTH ¡  Bandwidth Efficiency §  Dynamic Update §  AJAX Polling §  Long Polling §  Server Side Events §  Web Sockets §  JSON vs HTML fragments §  Trade-off §  Less bytes on network §  Identical fixed network costs §  Much more complex JavaScript code that must work across multiple devices §  HTML fragment approach → simple identical JavaScript universally across the site §  JSON → custom JavaScript for ever y item of updatable content
  • 34. HIGH PERFORMANCE – LESS LATENCY ¡  L e s s L a t e n c y §  Less server time §  Execute backend calls in parallel §  Avoid synchronization §  Threads §  DB (i.e. locking) §  NoSQL §  Eventual Consistency §  Use Futures to only block when absolutely required §  ETag → short circuit backend tasks §  Flush header while waiting for backend calls §  Allows CSS to be downloaded on client in parallel with backend calls §  HTTP/1.1 §  Trailer header allows addition of Content-Length, Last-Modifier and ETag with Transfer-Encoding: chunked §  Servlet 3.0 does NOT support this!! §  Under load scaling §  Avoid “too many” threads per request §  Threads should not be blocked waiting (i.e. IO / locks) §  No conversation state §  Must be managed across servers §  Session replication §  Sticky sessions §  Some state exists but not held on web server §  Decouple and isolates problem §  Separation of concerns §  Better encapsulation §  Improves opportunity for graceful degradation §  Web Tier Persistence §  Transient User Data (i.e. shopping basket, web UI preferences)
  • 35. HIGH PERFORMANCE – LESS LATENCY ¡  Less Latency §  Minimize DNS lookups §  Mobile Web analytics request §  230ms DNS lookup §  76ms TCP + HTTP connection §  58ms server time §  Flush Early §  Check flush isn’t buffered §  Apache, Network (i.e. Netscaler), gzip §  Only works on HTTP/1.1 connections §  Uses Transfer-Encoding: chunked! §  Caching §  Make pages cacheable §  Avoid cookie or header driven content §  Except User- Agent, Accept-Language, Accept-Encoding §  Use path variable instead of query parameters §  Most proxy caches do not cache resources with quer y parameters §  i.e. only latest version of Squid fixes this §  Use fingerprinting to dynamically control caching
  • 36. HIGH PERFORMANCE – LESS LATENCY ¡  L e s s L a t e n c y §  Caching §  Expires (HTTP/1.0) §  Date when resource is stale §  Cache-Control (HTTP/1.1) §  Overrides Expires header §  max-age - how long resource is fresh (in seconds) §  public, private – where item is cacheable §  no-store – never cache §  no-cache – always revalidate §  must-revalidate – revalidate if stale §  s-maxage, proxy-revalidate – proxy servers settings §  Vary (HTTP/1.1) §  Allows cached items to be varied by header §  If using disable HTTP/1.0 caches by Expires <= Date §  Tips §  Maximize freshness → 1 year §  Android clears cache based on length of freshness → >10 years §  Last-Modified §  Last time resource modified §  If-Modified-Since – conditional GET §  If-Unmodified-Since – conditional PUT, DELETE §  ETag §  Ensure consistency across multiple web servers §  Unique identifier for specific resource version §  If-None-Match – conditional GET §  If-Match – conditional PUT, DELETE §  Favor semantic “week validator” over byte level “strong validator” §  Week Validator enables short-circuiting the server HTML generation §  Trailer: ETag supports Transfer-Encoding: chunked (not supported by Servlet 3.0) §  304 Not Modified §  Last-Modified §  ETag
  • 37. HIGH PERFORMANCE – LESS LATENCY ¡  Less Latency §  Caching §  Not used enough 45% Cache-Control: max-age (days) 40% 35% 30% 25% 20% 15% 10% 5% 0% None t <= 0 0 < t <= 1 1 < t <= 30 30 < t <= 365 365 < t http://mobile.httparchive.org/
  • 38. HIGH PERFORMANCE – LESS LATENCY ¡  Less Latency §  Caching §  Browser §  Limited size §  Average mobile page size 550KB → < 7 pages to full reload OS (Device) Component Total Last-Modified ETag Survives Power Cycle Android 2.1 (Nexus One) 2MB 2MB Yes Yes Yes Android 2.2 (Glaxay S) 4MB 4MB Yes Yes Yes Android 2.3 (Nexus S) 4MB 4MB Yes Yes Yes Safari, iOS 3.1.3 (1st-gen iPhone) 0b 0b No No No Safari, iOS 3.2 (iPad) 26KB 282KB Yes Yes No Safari, iOS 4.0 (iPhone 3GS) 51KB 1MB Yes Yes No Safari, iOS 4.0 (iPhone 4) 102KB 2MB Yes Yes No webOS 1.4.1 (Palm Pre Plus) 1MB ? No No Yes http://www.yuiblog.com/blog/2010/06/28/mobile-browser-cache-limits/ http://www.blaze.io/mobile/understanding-mobile-cache-sizes/ http://mobile.httparchive.org/trends.php#bytesTotal&reqTotal
  • 39. HIGH PERFORMANCE – LESS LATENCY ¡  Less Latency §  Caching §  Reverse Proxy (i.e. ISP) §  Vary: Accept-Encoding §  many proxy caches do not detect Content-Encoding correctly §  Cookies §  Generally public caches won’t cache pages with cookies §  If they do cookies will be shared §  Edge / Gateway (i.e. CDN) §  Edge Side Include (ESI) §  Dynamic content assembly in cache §  Add icons: §  favicon.ico §  apple-touch-icon.png §  apple-touch-icon-precomposed.png
  • 40. HIGH PERFORMANCE – LESS LATENCY ¡  Less Latency §  Offline Storage §  Single origin policy §  No freshness or cache eviction §  No versioning §  No request → very fast and works offline §  Manifest file §  see earlier slides §  Web Storage §  Local Storage (or Session Storage) §  key/value storage of strings §  Simple but no query language §  No locks or transactions §  No indexes or complex data structures §  Slow, synchronous → blocking §  Up to 5MB §  Very fast §  Synchronous §  Only accessible from JavaScript §  Indexed DB §  Flat-file DB §  Hierarchical key/value persistence §  Basic indexing §  Fully asynchronous §  Supports indexed filtering and lookup §  DB level transactions & locking §  Up to 5MB, then prompt user for more §  Only accessible from JavaScript §  Web SQL Database §  SQLite in browser §  select, insert, update, delete, joins, inner selects, etc §  Up to 5MB, then prompt user for more §  Standard dropped by W3C §  Slow §  Only accessible from JavaScript §  File API
  • 41. HIGH PERFORMANCE – LESS LATENCY ¡  Less Latency §  Radio Resource Control §  HEAD request every 2-3 seconds to keep cell connection live §  Drains battery and adds congestion so don’t poll forever §  Page Beacons (Analytics) §  Make asynchronous §  Inject 1x1.gif §  Separate domain §  Avoid site cookies infecting request §  Avoid analytics cookies infecting site §  304 response §  Maximize benefit §  Page flow §  Device capabilities §  @media / JS cookie §  User- A gent §  Connection Type §  navigator.connection.type! §  ETHERNET, WIFI, CELL_2G, CELL_3G, …! §  Carrier §  Massive’s Operator Identification Platform
  • 42. HIGH PERFORMANCE – PAGE RENDER ¡  Faster Page Render §  Simple semantic DOM §  For every element (i.e. in Chrome) §  Node in DOM Tree §  RenderObject in RenderTree §  Efficient CSS selectors §  Avoid universal rules §  Don’t qualify id rules with tag names or classes §  Don’t qualify class rules with tag names §  Make rules as specific as possible §  Avoid descendant selectors (especially Tag or Universal) §  Apply rules at the highest level and allow inheritance §  Remove redundant qualifies §  ID selector with class or tag §  Class selector with tag
  • 43. HIGH PERFORMANCE – PAGE RENDER ¡  Faster Page Render §  CSS in head §  External or inline style blocks in body can cause reflow or FOUC §  Allows page to render progressively §  External stylesheets block rendering until downloaded and parsed §  Use hardware accelerated CSS animations §  Gets GPUs directly involved with compositing §  Avoids slow video to system memory copies §  Less redraws of complete screen §  only compositing layer redraw and recomposition §  Use CSS instead of JS animation §  Specify image dimensions §  Avoids reflow after image downloaded §  Specify character set §  Avoids browser auto detecting (and making / correcting mistakes) §  Timers §  Lots of >1s timers §  Very few (i.e. one) <500ms timers http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series-using.html
  • 44. HIGH PERFORMANCE – INTERACTION ¡  Faster Interaction §  Defer JS parsing §  100ms per 1KB §  Make browser ignore code §  Comments §  None script element §  When needed use eval(…)! §  Avoid blocking single UI Thread §  Long-running JS = Unresponsive UI §  Asynchronous §  Use events §  Synthetic (via setTimeout in framework) §  Native §  Script Yeilding §  setTimeout(function() {…}, 50)! §  Different browsers have different timer resolutions / issues §  Short timeouts can significantly shorten battery life §  setImmediate(function() {…})! §  Add to back of UI Thread Queue (i.e. no timer) §  Not supported yet (only in IE 10) §  WebWorkers §  Asynchronous, doesn’t block UI Thread §  Data is serialized into and out of worker §  No access to DOM §  Separate execution environment
  • 45. HIGH PERFORMANCE – INTERACTION ¡  Faster Interaction §  Touch delay §  Click event delayed between 300 and 500ms §  ontouchstart → ontouchend (with ontouchdrag within error margin) §  Event Handlers §  Event handlers on outer container §  Use event bubble §  Avoid lots of smaller event handlers
  • 46. HIGH PERFORMANCE – INTERACTION ¡  Faster Interaction §  Touch §  Work directly with content §  Avoid button indirection §  Although gesture support currently limited §  Limited touch events §  touchstart, touchmove, touchend §  Fat fingers §  Fitt’s Law §  difficulty ∝ distance, size §  Large buttons §  Inactive margin §  Right first time
  • 47. HIGH PERFORMANCE – PERCEPTION ¡  Improve Perception §  Flush early §  Visual feedback to user §  Button click changes color §  Image Interlacing §  Visible image after only 1/64 downloaded §  Adds ~15% §  Remove address bar §  While JavaScript is executing in background §  After onload §  window.scrollTo(0, 1);! §  If page height < window height then increase page height first to allow scroll
  • 48. TOOLS – DEBUGGING ¡  Debugging §  Chrome Internals §  chrome://net-internals §  chrome://appcache-internals/ §  chrome://profiler/ §  For full list see chrome://chrome-urls/ §  Works on Chrome for Android §  Firebug §  Desktop only §  BlackBerry Browser §  Remote debugging §  Smar tphone 7.0+ §  PlayBook §  Web Inspector §  http://trac.webkit.org/wiki/WebInspector §  Wienre §  http://phonegap.github.com/weinre/ §  DragonFly (for Opera Mobile) §  WebKit Remote Debugging §  http://www.webkit.org/blog/1620/webkit-remote-debugging/ §  Adobe Shadow §  Synchronize desktop browser with multiple mobile browsers §  http://labs.adobe.com/technologies/shadow/
  • 49. TOOLS – PERFORMANCE ¡  Performance / Analysis §  Chrome Inspector §  JS & CSS Profiler §  PageSpeed §  Chrome Inspector §  Firebug §  YSlow §  Chrome Inspector §  Firebug §  Mobile Perf Bookmarklets §  YSlow and other tools §  http://stevesouders.com/mobileperf/mobileperfbkm.php §  PCAP Web Performance Analyzer §  http://pcapperf.appspot.com/ §  Analyse packets → Waterfall & WebPageTest §  Shark for Root §  Android packet sniffer §  Works with 3G §  Analyse results (PCAP file) with pcapperf §  Speed Tracer §  Chrome Inspector Plugin §  Analyses all page interaction (CSS & JS) §  3PMobile §  On device browser §  Network Waterfall §  Browser Event (i.e. image loading time, CSS processing time) §  dynaTrace §  JS performance analyser §  http://ajax.dynatrace.com/ §  Loadtimer §  Tests time for full load of multiple URLs §  http://www.stevesouders.com/blog/2011/12/01/loadtimer-a-mobile-test-harness/ §  WebPageTest §  Waterfall of network traffic §  Timing of page load event adds noise
  • 50. TOOLS – EMULATORS ¡  Emulators §  www.mobilexweb.com/emulators ¡  Remote Labs §  DeviceAnywhere (bought by WebPageTest) §  deviceanywhere.com §  PerfectoMobile §  perfectomobile.com §  WebPageTest §  Samsung §  Free hosting of Samsung devices §  http://developer.samsung.com/remoteTestLab.do §  Nokia §  Free hosting of Nokia devices ¡  Experimental §  Cuzillion §  Build up different types of page §  internal / external CSS §  internal / external JS §  images §  Good for testing and learning about new devices / browsers §  http://stevesouders.com/cuzillion/