$30 off During Our Annual Pro Sale. View Details »

Mobile Web Best Practices

Mobile Web Best Practices

The key to a successful mobile site is high performance and reliability across a wide range of device capabilities and network latencies. However, the mobile web is a hostile environment with support for HTML5, JavaScript and CSS varying widely across browsers and devices. This talk will explain best practices to build high performance mobile sites that work across a wide range of devices and capabilities. The focus will be on lessons learnt at Betfair while rewriting the entire mobile web stack and how we used techniques to maximise performance and reliability. After discussing the problems faced in mobile the talk will explain how adaptive techniques can be used to provide progressive enhancement. This will be followed by an explanation of why and where performance bottlenecks occur and how these can be solved.

James D Bloom

May 27, 2012
Tweet

More Decks by James D Bloom

Other Decks in Programming

Transcript

  1. JamesDBloom
    MOBILE WEB BEST
    PRACTICES
    http://about.me/jamesdbloom
    http://blog.jamesdbloom.com

    View Slide

  2. PERCENTAGE OF MOBILE WEB
    0%
    5%
    10%
    15%
    20%
    25%
    30%
    35%
    40%
    45%
    50%
    http://www.tecmark.co.uk/wp-content/uploads/2011/08/Mobile-and-UK-Web-Traffic-August-2011.pdf

    View Slide

  3. ¡  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
    §  Software
    §  Faster Page Rendering
    §  Faster Interaction
    §  User
    §  Faster Interaction
    §  Improve Perception
    ¡  Tools
    §  Debugging
    §  Performance
    §  Emulators
    WHAT I’M TALKING ABOUT

    View Slide

  4. ¡  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

    View Slide

  5. 0
    1000
    2000
    3000
    4000
    5000
    6000
    7000
    SunSpider JS Benchmark (in ms)
    for some of the devices released in the last year
    ¡  Device
    §  Rapidly changing, widely diverse hardware
    §  “2500 different devices on Facebook per month” - Tobie Langel
    WHAT’S MOBILE – THE PROBLEM
    http://www.anandtech.com/show/5584/htcs-new-strategy-the-htc-one

    View Slide

  6. ¡  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
    WHAT’S MOBILE – THE PROBLEM
    Google Tech Talk - November 10, 2011 - Guy Podjarny

    View Slide

  7. ¡  Software
    §  Rapidly changing, widely diverse browsers and operating systems
    WHAT’S MOBILE – THE PROBLEM
    No Browser Creator
    1 Android Browser Google
    2 Apollo Team Apollo
    3 BlackBerry Browser Research in Motion
    4 Blazer Palm
    5 Bada Samsung
    6 Chrome for Android Google
    7 Classilla Cameron Kaiser
    8 Deepfish Microsoft
    9 Dolphin Browser MoboTap
    10 Firefox for mobile Mozilla Foundation
    11 ibisBrowser ibis
    12 Internet Explorer Mobile Microsoft
    13 Iris Browser Torch Mobile
    14 JOCA InteracT!V
    15 Kindle Basic Web Amazon.com
    16 MIB Motorola
    17 Minimo Mozilla Foundation
    18 Myriad / Openwave Myriad Group
    19 NetFront ACCESS
    20 Nokia Series 40 Browser Nokia
    No Browser Creator
    21 Obigo Browser Obigo AB
    22 Opera Mini Opera Software
    23 Opera Mobile Opera Software
    24 Palm HP
    25 Pixo Sun Microsystems
    26 PlayStation Portable Sony
    27 Polaris Browser Infraware
    28 Safari Apple
    29 Symbian / S60 Nokia
    30 Skweezer
    31 Skyfire Skyfire Labs
    32 Skyfire Mobile Browser Skyfire
    33 Steel
    34 Teashark
    35 Tristit
    36 UC Browser UC Mobile
    37 uZard Web Logicplant
    38 Vision Mobile Browser Novarra
    39 WebOS Browser Palm
    40 WinWAP Winwap Technologies

    View Slide

  8. ¡  Software
    §  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

    View Slide

  9. ¡  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”
    WHAT’S MOBILE – THE PROBLEM
    http://www.nytimes.com/2011/04/18/technology/18mobile.html?_r=3

    View Slide

  10. ¡  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
    MOBILE FIRST

    View Slide

  11. ¡  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
    AVOID JAVASCRIPT

    View Slide

  12. ¡  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

    View Slide

  13. ¡  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 – DEVICE DETECTION

    View Slide

  14. ¡  Breakpoints
    §  Minor breakpoint on client
    §  @media
    §  Screen size, resolution & pixel density
    §  Fluid grids, different 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 – ADAPTIVE DESIGN

    View Slide

  15. ¡  Progressive Enhancement
    §  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
    §  HTML5
    §  Not fully supported
    §  mobilehtml5.org
    §  www.modernizr.com
    §  caniuse.com
    §  www.browserscope.org
    §  www.quirksmode.org
    §  PolyFills
    §  Add weight
    §  Better to except not supported and degrade
    ADAPT – PROGRESSIVE ENHANCEMENT
    HTML
    Simple CSS
    Advanced CSS
    Basic JavaScript
    CSS Extensions
    AJAX / HIJAX
    HTML5

    View Slide

  16. ¡  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 every 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
    HIGH PERFORMANCE – WHY?
    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/

    View Slide

  17. ¡  Less Requests
    HIGH PERFORMANCE – LESS REQUESTS
    0.35
    0.4
    0.45
    0.5
    Total Requests Image Requests Total Xfer Size Image Xfer Size Domains
    Highest Correlation to Load Time
    0.3
    0.35
    0.4
    0.45
    0.5
    Total Requests Image Requests Total Xfer Size Image Xfer Size Domains
    Highest Correlation to Render Time
    http://mobile.httparchive.org/

    View Slide

  18. ¡  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

    View Slide

  19. ¡  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

    View Slide

  20. ¡  Less Requests
    §  Application Cache
    §  !
    §  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

    View Slide

  21. ¡  Less Requests
    §  Application Cache
    HIGH PERFORMANCE – LESS REQUESTS

    View Slide

  22. ¡  Less Bytes
    HIGH PERFORMANCE – LESS BYTES
    http://mobile.httparchive.org/
    0
    100
    200
    300
    400
    500
    Images Scripts Stylesheets HTML Other Total
    Average Bytes per Page by Content Type (in KB)
    0
    2
    4
    6
    8
    10
    12
    14
    16
    JPEG PNG GIF HTML JS CSS
    Average Individual Response Size (in KB)

    View Slide

  23. ¡  Less Bytes
    §  Simple semantic HTML
    §  No divitis, classitis, iditis
    §  However:
    §  classes can improve css selector performance
    §  Ids can improve testability
    §  Minify
    §  HTML, CSS, JS
    §  Optimize Images
    §  Use PNG instead of JPEG and GIF
    §  GIFs for small images (i.e. <10x10 pixels)
    §  JPEG for photographic-style images
    §  Maximize lossless compression
    §  JPEG: jpegtran, jpegoptim
    §  PNG: OptiPNG, PNGOUT
    §  WebPageTest
    HIGH PERFORMANCE – LESS BYTES
    JPEG
    47%
    GIF
    29%
    Other
    0%
    PNG
    24%
    Mobile Image Requests
    http://mobile.httparchive.org/

    View Slide

  24. ¡  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 BYTES

    View Slide

  25. ¡  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 jQuery over 3G
    §  jQueryMobile wraps jQueryUI with wraps jQuery Core
    §  Use → XUI, Zepto, microJS, baseJS
    HIGH PERFORMANCE – LESS BYTES
    http://www.slideshare.net/mobile/Gomez_Inc/optimizing-web-and-mobile-site-performance-using-page-speed

    View Slide

  26. ¡  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 BYTES

    View Slide

  27. ¡  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 – LESS BYTES

    View Slide

  28. ¡  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

    View Slide

  29. ¡  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
    HIGH PERFORMANCE – BANDWIDTH
    http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/

    View Slide

  30. ¡  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

    View Slide

  31. ¡  Bandwidth Efficiency
    §  Eager loading
    §  Download in background and store in localStorage
    §  Mobile Web: !
    §  Chromium: !
    §  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 Vary)
    §  Cache-Control: max-age >= 1 year
    §  Vary: Accept-Language
    HIGH PERFORMANCE – BANDWIDTH
    http://mobile.httparchive.org/

    View Slide

  32. ¡  Bandwidth Efficiency
    §  Dynamic Update
    HIGH PERFORMANCE – BANDWIDTH
    http://mobilehtml5.org/

    View Slide

  33. ¡  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 every item of updatable content
    HIGH PERFORMANCE – BANDWIDTH

    View Slide

  34. ¡  Less Latency
    §  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

    View Slide

  35. ¡  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 query parameters
    §  i.e. only latest version of Squid fixes this
    §  Use fingerprinting to dynamically control caching
    HIGH PERFORMANCE – LESS LATENCY

    View Slide

  36. ¡  Less Latency
    §  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

    View Slide

  37. ¡  Less Latency
    §  Caching
    §  Not used enough
    HIGH PERFORMANCE – LESS LATENCY
    0%
    5%
    10%
    15%
    20%
    25%
    30%
    35%
    40%
    45%
    None t <= 0 0 < t <= 1 1 < t <= 30 30 < t <= 365 365 < t
    Cache-Control: max-age (days)
    http://mobile.httparchive.org/

    View Slide

  38. ¡  Less Latency
    §  Caching
    §  Browser
    §  Limited size
    §  Average mobile page size 550KB → < 7 pages to full reload
    HIGH PERFORMANCE – LESS LATENCY
    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

    View Slide

  39. ¡  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

    View Slide

  40. ¡  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

    View Slide

  41. ¡  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-Agent
    §  Connection Type
    §  navigator.connection.type!
    §  ETHERNET, WIFI, CELL_2G, CELL_3G, …!
    §  Carrier
    §  Massive’s Operator Identification Platform
    HIGH PERFORMANCE – LESS LATENCY

    View Slide

  42. ¡  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

    View Slide

  43. ¡  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
    HIGH PERFORMANCE – PAGE RENDER
    http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series-using.html

    View Slide

  44. ¡  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

    View Slide

  45. ¡  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

    View Slide

  46. ¡  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 – INTERACTION

    View Slide

  47. ¡  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
    HIGH PERFORMANCE – PERCEPTION

    View Slide

  48. ¡  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
    §  Smartphone 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 – DEBUGGING

    View Slide

  49. ¡  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 – PERFORMANCE

    View Slide

  50. ¡  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/
    TOOLS – EMULATORS

    View Slide