Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Instant Loading: Making the web competitive on mobile

Instant Loading: Making the web competitive on mobile

Tech Talk at PayPal, Oct 10th, 2017.

Addy Osmani

October 10, 2017
Tweet

More Decks by Addy Osmani

Other Decks in Technology

Transcript

  1. Instant
    Loading
    Making the web competitive
    on mobile
    PayPal, Oct 17’
    @addyosmani

    View full-size slide

  2. Improving performance is a journey. Lots of
    small changes can lead to big gains.

    View full-size slide

  3. 1. JavaScript Frameworks
    2. Large JavaScript Bundles
    3. PRPL Pattern
    4.
    5.
    6. Reduction in HTTP Requests
    7. Service Workers
    8. Image Compression
    TOPICS

    View full-size slide

  4. loading is a user journey
    with many disparate expectations
    you’ve probably heard to REDUCE DNS LOOKUPS, REDUCE ROUND-TRIP TIMES, MINIMIZE REDIRECTS, ELIMINATE UNN

    View full-size slide

  5. USERS LOOK FOR VISUAL FEEDBACK TO reassure
    them everything is working as expected.

    View full-size slide

  6. first Interactive
    consistently Interactive

    View full-size slide

  7. Time to Interactive
    <5s
    on an average mobile
    device over 3G
    *2s on repeat-load a:er Service Worker registered
    GOAL

    View full-size slide

  8. 19s
    16s 420KB
    JavaScript Startup Performance, Double-Click Mobile Speed Matters report & the HTTP Archive
    The average web page on mobile in 2017
    UNTIL INTERACTIVE FULLY LOADED JAVASCRIPT

    View full-size slide

  9. PERFORMANCE
    JavaScript
    Start-up Start-up
    o o
    V8 Runtime Call Stats

    View full-size slide

  10. 1MB script
    (250KB minified)
    JS Parse Time On Mobile

    View full-size slide

  11. about:inspect in Chrome DevTools

    View full-size slide

  12. Apple A11 Arm64 SOC in iPhone8 benchmarks faster than x86 in Macbook Pro

    View full-size slide

  13. webpagetest.org/easy
    Moto G4 + 3G

    View full-size slide

  14. A closer look at PayPal.com

    View full-size slide

  15. Opportunities to dns-prefetch more?

    View full-size slide

  16. resources
    for the next navigation

    View full-size slide

  17. Authenticated PayPal.com

    View full-size slide

  18. Ideally, test on real (average)
    mobile hardware.
    CPU, GPU, cores, network packet loss
    can all introduce variance.

    View full-size slide

  19. 16 seconds in before
    First Paint

    View full-size slide

  20. 20 seconds before we see
    First Meaningful Paint

    View full-size slide

  21. 30 seconds before the page
    is Continuously Interactive

    View full-size slide

  22. Network bound for 3+ seconds

    View full-size slide

  23. 14s just fetching resources

    View full-size slide

  24. 11 seconds in idle time (time when the
    browser is waiting on the CPU or GPU to
    do some processing)

    View full-size slide

  25. ~6 seconds spent just in parsing & compiling
    JavaScript
    Party on the main
    thread

    View full-size slide

  26. By default, React includes many helpful warnings.
    These warnings are very useful in development.
    However, they make React larger and slower so you
    should make sure to use the production version
    when you deploy the app.

    View full-size slide

  27. 50% of script
    immediately
    loaded is unused

    View full-size slide

  28. Use babel-preset-env to only transpile code for browsers that need it
    {
    "presets": [
    ["env", {
    "targets": {
    "browsers": ["last 2 versions"]
    }
    }]
    ]
    }
    Only transpile what you need with

    View full-size slide

  29. Many sites optimize for the Lowest Common Denominator
    Most users end up being deployed ES2015 polyfills

    View full-size slide

  30. Deploying ES2015+ JavaScript in 2017
    babel-preset-env + <br/>

    View full-size slide

  31. Deploying ES2015+ JavaScript in 2017
    main-legacy.js main.js

    View full-size slide

  32. Switching to MozJPEG
    could save 60% on bytes

    View full-size slide

  33. Continuous
    Performance
    Tracking

    View full-size slide

  34. Code-splitting
    // Defines a “split-point” for a separate bundle
    require.ensure([], () => {
    const profile = require('./UserProfile', cb);
    });
    import('./UserProfile')
    .then(loadRoute(cb))
    .catch(errorLoading)
    Webpack 2+
    Webpack 1
    Also see Splittable, Closure Compiler
    or Browserify

    View full-size slide

  35. Minify _everything_
    Babelified ES5 w/Uglify
    ES2015+ with Babili
    css-loader + minimize:true
    Code-splitting
    Dynamic import()
    Route-based chunking
    Tree-shaking
    Webpack 2+ with Uglify
    RollUp
    DCE w/ Closure Compiler
    Optimize “Vendor” libs
    NODE_ENV=production
    CommonsChunk + HashedModuleIdsPlugin()
    Transpile less code
    babel-preset-env + modules:false
    Browserlist
    useBuiltIns: true
    Scope Hoisting:
    Webpack 3
    RollUp
    Strip unused Lodash modules
    lodash-webpack-plugin
    babel-plugin-lodash
    Fewer Moment.js locales
    ContextReplacementPlugin()

    View full-size slide

  36. Webpack support for Pure Modules

    View full-size slide

  37. Plenty of lightweight options for mobile
    Lower total cost on size + parse times from the get-go

    View full-size slide

  38. Preact on Lyft

    View full-size slide

  39. Preact on Uber

    View full-size slide

  40. Byte savings @

    View full-size slide

  41. Brotli
    Display Ads from Google now served
    using Brotli compression!
    40%
    Data-savings up to
    15% in aggregate over gzip
    https://developers.googleblog.com/

    View full-size slide

  42. Brotli
    Improved load time by 7% in India & 4% U.S
    bit.ly/linkedin-brotli
    Decreased the size of static assets by 20%
    bit.ly/dropbox-brotli
    17% improvement for largest JS bundles
    bit.ly/certsimple-brotli
    1.5 petabytes (million gigs) saved a day
    bit.ly/playstore-brotli

    View full-size slide

  43. WebP
    30% smaller than JPEG
    25% smaller than PNG

    View full-size slide

  44. WebP
    bit.ly/webp-format
    Serving over 43B image requests a day
    25-30%
    savings for WebP on average (26% lossless)
    Data Saver + Web Store

    View full-size slide

  45. WebP Conversion
    XNConvert
    Windows/Mac/Linux
    Can convert in batch
    Supports most formats
    Alternatively:
    imagemin
    Pixelmator
    ImageMagick
    GIMP
    Leptonica

    View full-size slide

  46. WebP Serving










    Or use the Accept header + .htaccess to serve WebP if a browser supports it and it exists on disk.

    View full-size slide

  47. Service Workers
    Inbox by Gmail
    10%
    improvement in Time-to-Interactive

    View full-size slide

  48. HTTP Caching Checklist
    Use consistent URLs and minimize resource churn
    Provide a validation token (ETag) to avoid transferring unchanged bytes
    Identify resources that can be cached by intermediaries (like CDNs)
    Determine the optimal cache lifetime of resources (max-age)
    Consider a Service Worker for more control over your repeat visit caching
    1.
    2.
    3.
    4.
    5.
    bit.ly/caching-checklist

    View full-size slide

  49. Let’s hack

    View full-size slide

  50. ResourceLoadPriorityVeryHigh

    View full-size slide

  51. ResourceLoadPriorityVeryHigh

    View full-size slide

  52. PayPal-inium

    View full-size slide

  53. Original
    Everything is high priority
    Preloaded JS
    Preloaded CSS + fonts

    View full-size slide

  54. Original
    Everything is high priority
    JS + CSS is high priority
    CSS + fonts are high prio

    View full-size slide





  55. ..
    Link: 1.js; rel="preload"; as="script"

    View full-size slide

  56. bit.ly/prpl-paFern
    PRPL
    bit.ly/prpl-paFern

    View full-size slide

  57. HTTP/2 with 3G

    View full-size slide

  58. HTTP/2 + preload with 3G

    View full-size slide

  59. Express + HTTP/2 Push Headers
    const express = require('express'),
    let app = express();
    app
    .use('/js', express.static('js'))
    .get('/', function (req, res) {
    res.set('Link', `
    ; rel=preload; as='style',
    ; rel=preload; as='script',
    ; rel=preload; as='script'`)

    View full-size slide

  60. Alternatively: Track cache content using cookies
    if (supports_http2() && !http_cached('/app.js')) {
    header('link:; rel=preload; as=script’);
    setcookie('/app.js', 'is-cached', 0, '/');
    }

    View full-size slide

  61. Alternatively: Track cache content using cookies
    function http_cached($filename) {
    if ('is-cached' === $_COOKIE[$filename]) {
    return true;
    } else {
    return false;
    }
    }
    Try CASPer

    View full-size slide

  62. Repeat visit with Service Worker

    View full-size slide

  63. Next: Differential Serving based on
    browser compatibility?
    HTTP/1 works better when resources are concatenated (bundled)
    HTTP/2 works better when resources are more granular (unbundled)
    Serve an unbundled build for server/browser combinations supporting
    HTTP/2. Trigger delivery with or HTTP/2 Push
    Serve a bundled build to minimize round-trips to get the app running on
    server/browser combinations that don't support HTTP/2 Push

    View full-size slide

  64. Debugging: HTTP/2 Server Push in DevTools

    View full-size slide

  65. Debugging: HTTP/2 Server Push in DevTools

    View full-size slide

  66. HTTP/2 Server Push Rules Of Thumb
    Push just enough resources to fill idle network time, and no more.
    Push resources in evaluation-dependence order.
    Consider using strategies to track the client-side cache.
    Use the right cookies when pushing resources.
    Use server push to fill the initial cwnd. Consider
    preload links to reveal remaining critical resources.
    1.
    2.
    3.
    4.
    5.
    bit.ly/h2push
    PUSH

    View full-size slide

  67. PRPL In-A-Box
    Polymer App
    Toolbox
    PREACT
    CLI

    View full-size slide

  68. With Service Workers

    View full-size slide

  69. With HTTP/2 Server Push

    View full-size slide

  70. babel-preset-env + per-browser bundles

    View full-size slide

  71. babel-preset-env + per-browser bundles

    View full-size slide

  72. Twitter Lite

    View full-size slide

  73. Interactive in <5s on 3G

    View full-size slide

  74. Can we get fast 3G numbers
    across the board or regular
    3G?

    View full-size slide

  75. PRPL
    Push / Preload

    View full-size slide

  76. 18% improvement

    View full-size slide

  77. 36% improvement

    View full-size slide

  78. HTML Streaming
    reduced TTFB by 30%
    (200ms), increasing time
    user’s spent in the app.
    Nicolas Gallagher, Technical lead for Twitter Lite

    View full-size slide

  79. 4x improvement to
    render perf by using
    requestIdleCallback() to
    defer JS loading of
    images.
    Nicolas Gallagher, Technical lead for Twitter Lite

    View full-size slide

  80. Heavy image decode
    Lower image decode

    View full-size slide

  81. Adapt intelligently
    H
    E
    I
    G
    H
    T
    Size appropriately
    WIDTH
    IMAGE DECODE
    Compress carefully Take care with tools
    Prioritize critical images
    HIGH
    LOW
    Lazy-load the rest
    Choose the right format
    Image
    Optimisation

    View full-size slide

  82. images.guide

    View full-size slide

  83. Data Saver Mode introduced up to 70% savings for Twitter Lite
    Do this with the browser using the Save-Data client hint

    View full-size slide

  84. This is a headline
    Followed by a subhead
    This is body copy and it goes a little like this and Lorem ipsum
    dolor sit amet, consectetur adipiscing elit. This is body copy and
    it goes a little like this and Lorem ipsum dolor sit amet,
    consectetur adipiscing elit.
    Application Shell
    A skeleton representing the
    user interface that can be
    offline cached & instantly
    rendered on repeat visits.

    View full-size slide

  85. Before Service Worker
    After Service Worker

    View full-size slide

  86. Before code-splitting

    View full-size slide

  87. webpack-web.config.js
    const plugins = [
    // extract vendor and webpack's module manifest
    new webpack.optimize.CommonsChunkPlugin({
    names: [ 'vendor', 'manifest' ],
    minChunks: Infinity
    }),
    // extract common modules from all the chunks (requires no
    'name' property)
    new webpack.optimize.CommonsChunkPlugin({
    async: true,
    children: true,
    minChunks: 4
    })
    ];

    View full-size slide

  88. After code-splitting
    bit.ly/twitterlite-perf
    bit.ly/twitter-casestudy

    View full-size slide

  89. https://meowni.ca/font-style-matcher/

    View full-size slide

  90. https://www.zachleat.com/web/comprehensive-webfonts/
    “Comprehensive
    Web Fonts”

    View full-size slide

  91. type="font/woff">
    Link: ; rel=preload; as=font;
    type='font/woff'

    View full-size slide

  92. Heaviest use of rel=preload is for Web Fonts
    HTTPArchive

    View full-size slide

  93. Preloading Web Fonts = 50% (1.2s)
    improvement in time-to-text-paint

    View full-size slide

  94. Control font performance
    with font-display
    auto: uses whatever font display strategy the user-agent uses
    block: draws "invisible" text at first if the font is not loaded, but swaps
    the font face in as soon as it loads
    swap: draws text immediately with a fallback if the font face isn’t
    loaded, but swaps the font face in as soon as it loads
    fallback: font face is rendered with a fallback at first if it’s not loaded,
    but the font is swapped as soon as it loads
    optional: if the font face can’t be loaded quickly, just use the fallback
    Chrome 60

    View full-size slide

  95. bit.ly/font-subsetting

    View full-size slide

  96. https://fonts.googleapis.com/css?family=Inconsolata
    https://fonts.googleapis.com/css?family=Inconsolata&text=Hello
    Web Font Subsetting
    ~3KB
    ~880 bytes
    Supported by Google Fonts

    View full-size slide

  97. /* Small subset, normal weight */
    @font-face {
    font-family: whatever;
    src: url('reg-subset.woff')
    format('woff');
    unicode-range: U+0-A0;
    font-weight: normal;
    }
    The browser can also handle subsetting!
    https://jakearchibald.com/2014/minimising-font-downloads/
    /* Large subset, normal weight */
    @font-face {
    font-family: whatever;
    src: url('reg-extended.woff')
    format('woff');
    unicode-range: U+A0-FFFF;
    font-weight: normal;
    }
    Chrome 36
    Firefox 44

    View full-size slide

  98. CSS Font Loading API
    https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/webfont-optimization
    const font = new FontFace("Awesome Font", "url(/fonts/awesome.woff2)", {
    style: 'normal', unicodeRange: 'U+000-5FF', weight: '400'
    });
    // don't wait for the render tree, initiate an immediate fetch!
    font.load().then(function() {
    // apply the font (which may re-render text and cause a page reflow)
    // after the font has finished downloading
    document.fonts.add(font);
    document.body.style.fontFamily = "Awesome Font, serif";
    // OR... apply your own render strategy here...
    });
    Chrome 35
    Firefox 41

    View full-size slide

  99. Use System Fonts when you can
    The fastest font is one that doesn’t need to load.
    Try font-display: optional;
    If a Web Font can’t load fast, load a fallback instead. If the Web Font is
    cached, it’ll get used the next time the user loads the page.
    Try to request Web Fonts with a higher priority
    If Web Fonts are a critical to your UX, preload them to minimize FOIT.
    Try subsetting to limit the range of Web Font characters needed
    Subsetting removes characters & Open-Type features from fonts, reducing
    file size. Google Fonts, TypeKit & Font Squirrel support it. Be careful with use.
    Try the CSS Font Loading API if you need more control
    Track font download progress & apply once fetched, manipulate font faces
    and override default lazy load behavior.
    S
    Have a Web Font Loading Strategy
    @addyosmani

    View full-size slide

  100. Streams API
    bit.ly/streams-ftw
    Progressive Loading: HTML

    View full-size slide

  101. in body
    bit.ly/progressive-css
    Progressive Loading: CSS

    View full-size slide

  102. in body
    bit.ly/progressive-css
    Progressive Loading: CSS











    View full-size slide

  103. medium.com/reloading

    View full-size slide

  104. https://medium.com/dev-channel/treebo-a-react-and-preact-progressive-web-app-
    performance-case-study-5e4f450d5299
    next do webpack bundle analyzer

    View full-size slide