Mobile Web Performance

http://instartlogic.github.io/p/mobileperf

Don't Break the Mobile Web

Web View

Fast to ....

  • Load
  • Render
  • Respond
  • Understand
  • Beautiful
  • Useful
  • Eco-friendly

mypcwallpaper.com

Mobile Web Performance

  1. Current Ecosystem
  2. Performance Concerns
  3. Issues and Solutions

Estelle Weyl

Open Web Evangelist
Instart Logic

Twitter:
@webdevtips
@estellevw
@standardista

Blog:
www.standardista.com

Github:
github.com/estelle

  • HTML5 and CSS3 for the Real World
  • Animations and Transitions with CSS
  • MObile HTML5
  • Web Performance Daybook
  • CSS: The Definitive Guide
  • Flexible boxes in CSS

Mobile Ecosystem

Top Devices of 2016

Phone Cost RAM ROM CPU
Samsung GALAXY S7 $670 4 GB 32 - 64 GB 1.6 GHz
Apple iPhone 6s $600 1 GB 32 - 128 GB 1.8 GHz
LG G5 $550 4 GB 32 GB 2.5 GHz
Huawei Nexus 6P $550 3 GB 32 - 128 GB 2.0 GHz
Samsung Galaxy Note 5 $700 4 GB 32 - 64 GB 2.1 GHz
Sony Xperia $600 2 GB 16 GB 1.5 - 2.0 GHz
Samsung Galaxy S6 $785 3 GB 32 - 128 GB 2.1 GHz
LG Nexus 5X $580 2 GB 32 GB 1.8 GHz
Moto X Pure Edition $299 3 GB 16 - 64 GB 1.8 - 2.5 GHz
Xiaomi Redmi Note 3 $180 2 - 3 GB 16 - 32 GB 2X1.8 GHz

Emerging Markets

Wireless Coverage in Emerging Markets

Top Devices: Indonesia

Phone Cost RAM ROM CPU
Nokia Asha 200 $27 32 MB 10 - 64 MB FF
Nokia Asha 210 $27 32 MB 64 MB FF
Nokia X2-01 $9 64 MB 55 MB FF
Nokia C3-00 $45 64 MB 55 MB FF
TECNO P5 $42 512 MB 4 GB 1.0 GHz
Nokia Asha 205 $27 64 MB FF
Nokia Asha 201 10 - 32 MB 64 MB FF
TECNO M3 $41 512 MB 4 GB 1.0 GHz
Infinix Hot Note X551 $142 1 GB 16 GB 1.4 GHz
Infinix Hot 2 X510 $112 1 - 2 GB 16 GB 1.3 GHz

FF = Feature Phone
Java with WAP 2.0/xHTML.
Opera/UC Browser

Browser shares available memory

Running Services
Other73MB Avail: 255MB + 182MB in 21
Calendar8.4MB
Process:com.htc.bgp
ObexService31:52:14
Started by application: Touch to stop
AT&T Navigator8.4MB
Process: com.telnav.app.android.congular
ResoucePreLoaderRestarting
Started by application: Touch to stop
AT&T Spots2.4MB
Process: com.matchboxmobile.wasp
WispService31:52:14
Started by application: Touch to stop
Media4.1MB
Process: android.process.media
DownloadService31:52:14
Started by application: Touch to stop
PVWmdrmService2.2MB
Process: com.pv.wmdrmservice
PVWmdrmService31:52:14
Started by application: Touch to stop

Android Device Fragmentation (2015)

distribution of devices by popularity, showing over 1000 devices

Via OpenSignal

Device Sizes & Aspect Ratios (2015)

distribution of devices by size, showing over 49mm x 57mm to 163mm x 302mm devices

Via OpenSignal

49mm x 57mm to 163mm x 302mm

Device Features

RAM, GPU, Device size, and NFC support have been steadily increasing over the years.

Via OpenSignal

Dev Environments ≠ Mobile Experience

airplane paper plane drone

Battery

Mobile Performance Concerns

November 2010

In 2010, content was Images=416kb, HTML=34kb, Stylesheets=25kb, Scripts=113kb, Fonts=2kb, and Other=22kb for a total of 702kb

July 1, 2017

In July 2017, content is Images=1714kb, HTML=25kb, Stylesheets=60kb, Scripts=347kb, Fonts=97kb, Video=329 and Other=14kb for a total of 3034 kb

2017 v 2010

432%
screenshot of Chris Zacharias's blog post from December 2012, 
Page Weight Matters Open in separate window

Youtube Feathers:
Regular:  58 requests/1200 kB
Feathers: 14 requests/100 kB

Web Performance

Download
# of resources: images, fonts, HTML, scripts, and CSS loaded
Parse
File size of above resources
Execute
Parsing & Painting
Perceived Performance
User perception of load speed and reaction time.(study)

Device Considerations - Phones aren't Laptops

  • Very powerful browsers
  • Less powerful CPUs
  • Not plugged In
  • Metered data
  • Tiny Screens
  • Different Interactions
    (Touch / Keyboard / Mouse)
  • Battery
  • Latency
  • Memory
  • Responsiveness

Issues and Solutions

Knowns

  • # of HTTP Requests
  • # of Bytes
  • Images, Animations, Interactions
  • Squishiness
  • Responsiveness

Unknowns

  • Network (latency, bandwidth)
  • Hardware (processing power)
  • Browser (blocking, features)

While we control how we build the site, we don't have control over ...

Latency

whether tethered or on work wifi, when you need to make a DNS request, it's a simple request from browser to DNS server, back to browser, to the host computer

Latency

On mobile, the request goes from your device to the tower, to the phone company to the dns server, back to the phone company, back to the tower then to your phone. A second round trip is then needed to get the actual content

What's involved in a page load?

  • HTTP request
  • DNS lookup
  • TCP Connect
  • HTTP request sent
  • Server Magic
  • Server Sends response
  • Browser receives/parses response
  • Resources fetched from Cache
  • Parse & Execute Scripts
  • Render Site
  • Each request: go back to DNS lookup or HTTP Request
  • Stylesheets are blocking
  • Scripts are blocking.

Navigation Timing API metrics

Navigation Timing API metrics

Latency"Last Mile"

(Note the colors)

Screenshot of WebPageTest waterfall chart showing light colors in a load reflect time to first byte

TTFB = Latency + Server Time
Limit # of handshakes & bandwidth req

Better Performance

Screenshot of WebPageTest waterfall chart showing light colors in a load reflect time to first byte

TTFB = Latency + Server Time
Limit # of handshakes & bandwidth req

RAIL

Four phases of interaction: end-user’s perception

  1. Response to Input touch_app
  2. Animation & Scrolling directions_run
  3. Idle alarm
  4. Page Load cached

Video: How Users Perceive the Speed of The Web (2015): Paul Irish / Google

In Our Control

  • # of HTTP Requests
  • # of Bytes
  • Images, Animations, Interactions
  • Squishiness
  • Responsiveness

Out of Our Control

  • Network (latency, bandwidth)
  • Hardware (processing power)
  • Browser (blocking, features)

Tools & Rules

  • YSlow
  • PageSpeed
  • WebPageTest
  • Developer Tools
  • Lighthouse
  • Minimize Requests
  • Reduce DNS lookups
  • Avoid Redirects
  • Cache Headers
  • Only load needed resources
  • Minimize size & optimize media
  • Put CSS in the <head>
  • Put JS at the bottom
  • Don't scale images in HTML
  • Concatenate, Minify, Refactor
  • Don't block the UI thread
  • Use HTTP/2
  • Use a CDN
  • Use SSL
  • Use AMP
  • Offer Progressive Web Apps
  • Develop Mobile first
  • Minimize the number of DOM nodes
  • Avoid reflows and repaints
  • Use the right input type
  • Configure the viewport
  • Make the site squishy
  • Ensure legibility
  • Serve the right size images
  • Effective content strategy
  • Create a performance budget and stick to it
  • etc.

Lighthouse

https://developers.google.com/web/tools/lighthouse/

  1. Progressive Web App (PWA checklist)
  2. Performance
  3. Accessibility (Google Intro)
  4. Best Practices

PageSpeed

Minimize request size
GZip all requests.
Leverage browser caching.
Include caching headers for all requests with a future date so previously fetched responses can be reused instead of refetched.
Specify a cache validator
Specify a Last-Modified or ETag header to enable cache validation. ETags provide revalidation tokens automatically sent by client to check if there are file changes since last requested.
Minify CSS, JS & HTML
Removing unnecessary whitespace saves bandwidth
Defer parsing of JavaScript
include async attribute in your <script> tags so client can continue downloading assets instead of waiting as scripts are downloaded, parsed and excecuted.
Optimize images
Choose best format and compression on a per image basis include: type of data being encoded, image format capabilities, quality settings, resolution, and more. Leverage SVG and CSS. See previous page.
Specify a character set
Including a content-type header, such as Content-Type: text/html; charset=UTF-8 reduces browser processing. Can start parsing HTML immediately when it knows which character set it has.
Remove query strings from static resources
Resources with a "?" in the URL are not cached by some proxy caching servers
Specify a Vary: Accept-Encoding header
In case client doesn't support compression, tells proxy server to store both compressed and uncompressed versions.
Avoid CSS @import
Only starts downing imported file once encountered rather than in parallel.
Avoid a character set in the meta tag
Better to include it in HTTP Content-Type header (IE8 rule)
Avoid bad requests
404 and 410 errors waste time. If requests are for blocking resources, it becomes a more serious problem.
Avoid landing page redirects
If your site requires redirects, do them server-side not client side, to reduce round trip requests. Removing HTTP redirects removes extra round trips.
Combine images into CSS sprites
Enable Keep-Alive
HTTP persistent connections allows a TCP connection to send and receive multiple HTTP requests, reducing latency for subsequent requests.
Enable compression
GZip!
Inline Small CSS & JS
Minimize redirects
Minimizing redirects removes additional RTTs and wait time for users.
Optimize the order of styles and scripts
Prefer asynchronous resources
Many JS libraries and frameworks were originally written as synchronous scripts, but now have asynchronous versions. Use the asynchronous versions.
Put CSS in the document head
Serve resources from a consistent URL
Serve scaled images
Properly sized images saves bandwidth.
Specify image dimensions
Enables rendering page before images are downloaded. Without proper dimensions, browser will need to reflow and repaint upon image downloaded.
Page Speed

Usability Rules

Avoid plugins
Configure the viewport
Optimize pages to display well on mobile devices by including a meta viewport in the head of the document specifying width=device-width, initial-scale=1.
<meta name=viewport content="width=device-width, initial-scale=1">
Size content to viewport
Scrolling websites vertically is Okay, but horizontally creates poor user experience. Use media queries and vh, vw and percents for width.
Size tap targets appropriately
Set a minimum tap target size of of 48 CSS pixels on a site with a properly-set mobile viewport. Make important tap targets large enough to be easy to press, ensuring there is extra spacing between smaller tap targets.
Use legible font sizes
Page Speed Insights

Image Optimization

GZip
Remove Image Metadata
Resize Images
Optimize Images
Use the Right Image Format
Reduce the Number of Images

My Tips & Deep Dive

Note: Include an alt attribute on all foreground images, with empty alt attribute for decorative images.

#1: Configure the Viewport

<meta name="viewport"
   content="width=device-width, ...">
width width of device's virtual viewport.
device-widthwidth of the device's screen.
height height of device's virtual viewport
device-height height of the device's screen.
initial-scale Initial zoom on page visit. default 1.0.
minimum-scale If user scalable, as small as it can zoom on the page.
maximum-scale If user scalable, maximum amount visitor can zoom on the page.
user-scalableCan the web zoom in and out. Values are yes or no.

One line of code....

Don't be a jerk like GMail

<meta name="viewport" 
  content="initial-scale=1.0, 
           maximum-scale=1.0, 
           minimum-scale=1.0, 
           user-scalable=no, 
           width=device-width">
Gmail doesn't allow resizing

#2 Optimize all Images

  1. GZip
  2. Remove Image Metadata
  3. Resize Images
  4. Optimize Images
  5. Use the Right Image Format
  6. Reduce the Number of Images
  7. Leverage CSS

#2 Optimize all Images

  1. GZip

    Minify and GZip SVG and font files. In that order. See tips for optimising SVG delivery.

  2. Remove Image Metadata

    Metadata adds bytes and can be a security risk by exposing geographical data. You can Strip EXIF metadata from multiple images at a time.

#2 Optimize all Images

  1. Resize Images

    Serve the smallest image file for the screen size and resolution.

Right Size Your Images: Unneeded pixels

  • 240 x 240 = 57,600
    200 x 200 = 40,000
                17,600
  • 440 x 440 = 193,600
    400 x 400 = 160,000
                 33,600
  • 640 x 640 = 409,600
    600 x 600 = 360,000
                 49,000
  • 840 x 840 = 705,600
    800 x 800 = 640,000
                 65,600

CloudFour: image breakpoints

Scaling can be slow....

Scaled: 1,850 milliseconds

Right-sized: 625 milliseconds

blue = CPU used to decode
green = FPS (more is better)
purple = rendering
PhysicsOfFast

#2, sect. 3, part B
<picture>, <source> & srcset

<picture>
  <source srcset="large.jpg" 
          media="(min-width: 1000px)">
  <source srcset="small.jpg" 
          media="(min-width: 500px)">
  <img src="default.jpg"
       srcset="highresolution.jpg 2x" 
       alt="do not forget the alt">
</picture>

#2 Optimize all Images

  1. Optimize Images

#2 Optimize all Images

  1. Use the Right Image Format

    Image types include SVG, GIF, JPEG, PNG, and WebP.

    • GIF: <= 256 color pallette, need transparency and/prlow quality animation
    • SVG: scalable, animatable, unlimited color pallette
    • PNG: > 256 colors if transparency needed.
    • JPEG: raster images
    • WebP: Animation, transparency, great resolution, small file size. Blink only.
    • JPEG-XR: For Edge

Smallest file size

Browser

Optimal image format

Chrome

WebP

IE 9+ / Edge  

JPEG-XR

Opera

WebP

Safari

JPEG-2000

You don't have to change the file extension.

  1. Reduce the Number of Images
    • Sprites
    • Just fewer images
  2. Leverage CSS
    • Image Masking. (article)
    • CSS Effects: gradients, borders, rounded corners, shadows, etc.
    • Sprites: especially without HTTP/2
    • CSS Filters
    • Media Queries serve hi-res images to hi-res devices
    • Animation: steps() as alternative to animated gifs.
    • Leave out prefixed property/values

#3: Optimize Video

  1. Omit videos
  2. Compression
  3. Optimize source order
  4. Remove muted audio

July 1, 2017

In July 2017, content is Images=1714kb, HTML=25kb, Stylesheets=60kb, Scripts=347kb, Fonts=97kb, Video=329 and Other=14kb for a total of 3034 kb

July 1, 2015

In July 2015, content is Images=1348kb, HTML=55kb, Stylesheets=68kb, Scripts=344kb, Fonts=102kb, Video=204 and Other=4kb for a total of 2135 kb

#3.1 Omit the video

<video .... id="hero-video">

Do you really need a hero image? On a mobile device?

@media screen and (max-width: 650px) {
  #hero-video {
    display: none;
  }
}

#3.3: Optimize Source order

Order from smallest to largest*

<video width="400" height="300" controls="controls">
  <!-- WebM: 10 MB -->
  <source src="video.webm" type="video/webm" />
  <!-- MPEG-4/H.264: 12 MB -->
  <source src="video.mp4" type="video/mp4" />
  <!-- Ogg/Theora: 13 MB -->
  <source src="video.ogv" type="video/ogv" />
</video>
* check for quality consistency

#3.4 Remove audio that is muted

<video autoplay="" loop="" muted="true" id="hero-video">
  <source src="web_banner.webm" 
          type='video/webm; codecs="vp8, vorbis"'>
  <source src="web_banner.mp4" type="video/mp4">
</video>
ffmpeg -i original.mp4 -an -c:v copy audiofree.mp4
  • -an: Disable audio recording in output.

#4: Everything Else

Code Order

<!DOCTYPE HTML>
<html>
 <head>
   <meta charset="UTF-8">
   <title>Titles are good for SEO</title>
   <link rel="stylesheet" href="prettyWhenItLoads.css"/>
 </head>
 <body>
   <!-- lots of good content -->
   <script src="dontBlockHTMLandCSS.js"></script>
 </body>
</html>

JavaScript

  • Render cost: JS (and CSS and images)
  • JS (download, parsing & executing)
  • Dynamic JS: ⬆ rendering cost (can't be cached).
  • AJAX: waking up the radio communications
  • All scripts loaded and parsed (even if not used)
  • Reduce JS to only what is needed
  • Don't let 3rd party scripts be your SPOF
  • Are libraries really necessary?
    • Include only functions used by page to reduce energy use.
    • Goal of most libraries is equalize across browsers
      (not necessry in mobile space)
    • Libraries simplify web development, but increase energy use.
    • You don't need a framework for that

Battery Consumption

CPU Drains the battery. Avoid using it!

  • Avoid Reflows & Repaints
  • Minimize JavaScript (size and activity)
  • Avoid JavaScript Animations (requestAnimationFrame())
  • Avoid WebGL (or otherwise warming up the phone)
  • Let the radio idle
  • Implement what you learn today

Let your device take long, long breaks!

JavaScript in Pink

Screenshot of WebPageTest waterfall chart showing light colors in a load reflect time to first byte

The effect of RDD...

Screenshot of WebPageTest waterfall showing a 2 second DOM content loaded event

Minimize the DOM

  • Minimize number of nodes
    • Uses up memory & time
    • Measures each node for each repaint
  • Cache DOM lookups
    • Store them!
  • Minimize DOM manipulations
    • Batch DOM queries & DOM manipulations separately

More nodes = more expensive!

Squishy ≠ Responsive

Disney Went "Mobile"

Wide / Desktop Narrow / Mobile
Requests 77 123
Assets 3752kB 3344kB
Load 10.62s 34.10s
DOMContentLoaded  9.74s 30.94s
desktop stats mobile stats

HTTPS

Progressive Web Apps

screenshot of Flipkart in offline modescreenshot of Flipkart in offline mode
  • Works offline, online & on Lie-Fi
  • App like
    • Installable: add to home screen
    • Splash Page: add to home screen
  • Secure: HTTPS
  • Manifest
  • Service Workers
  • Responsive
  • Progressively Enhanced

AMP: Accelerated Mobile Pages

AMP

Build with Accessibility in Mind

Build with Mobile in mind

Test in Real Environments

Phone showing which apps are running in the background
  • Test on Phone:
    • Simulator != Emulator
    • Cap your memory
  • Test with many apps open
  • Test on multiple devices
  • Test on mobile network

Test during development

Set a budget before you start

Tricks

  • Scale down (not up)
  • Don't use prefixed property fallbacks
  • Take advantage of HTML5 & native storage
  • Don't disable zoom (except for games)

Conclusion

  • Follow performance recommendations
  • Minimize Latency
  • Manage memory
  • Use CSS Judiciously
  • Use JS Minimally (and NOT for animation)
  • Batch query and manipulations separately
  • Reuse the DOM
  • Keep Mobile in Mind

Remember...

Your users may
not be tethered,
their memory may be limited,
and their bandwidth may be
unreliable and metered.