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.
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”
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/
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/