web optimization with service woker
TRANSCRIPT
Agenda
Introduction to ServiceWorker
Strategy for ServiceWorker
sw-toolbox
Result Comparison
Introduction to ServiceWorker
• Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.
• It's a JavaScript Worker, so it can't access the DOM directly. Instead, a service worker can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM if needed.
• Host server need use SSL
• Cache request MUST trigger under register routing path
What is ServiceWorker
SSL and Cache Scope
• Browser support. • http://caniuse.com/#feat=serviceworkers
• Jake Archibald's is Serviceworker ready site.
• Need HTTPS
Prerequisites
The service worker life cycle
• On install - as a dependency
• On install - not as a dependency
• On activate
• On user interaction
• On network response
• Stale-while-revalidate
• On push message
• On background-sync
When to store resources
On install - as a dependencyself.addEventListener('install', function(event) {
event.waitUntil(
caches.open('mysite-static-v3').then(function(cache) {
return cache.addAll([
'/css/whatever-v3.css',
'/css/imgs/sprites-v6.png',
'/css/fonts/whatever-v8.woff',
'/js/all-min-v4.js'
// etc
]);
})
);
});
On install - not as a dependencyself.addEventListener('install', function(event) {
event.waitUntil(
caches.open('mygame-core-v1').then(function(cache) {
cache.addAll(
// levels 11-20
);
return cache.addAll(
// core assets & levels 1-10
);
})
);
});
On activeself.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
On user interactiondocument.querySelector('.cache-article').addEventListener('click', function(event) {
event.preventDefault();
var id = this.dataset.articleId;
caches.open('mysite-article-' +id).then(function(cache) {
fetch('/get-article-urls?id=' +id).then(function(response) {
// /get-article-urls returns a JSON-encoded array of
// resource URLs that a given article depends on
return response.json();
}).then(function(urls) {
cache.addAll(urls);
});
});
});
On network responseself.addEventListener('fetch', function(event) {
event.respondWith(
caches.open('mysite-dynamic').then(function(cache) {
returncache.match(event.request).then(function(response) {
return response ||fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
Stale-while-revalidateself.addEventListener('fetch', function(event) {
event.respondWith(
caches.open('mysite-dynamic').then(function(cache) {
returncache.match(event.request).then(function(response) {
var fetchPromise =fetch(event.request).then(function(networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
})
return response || fetchPromise;
})
})
);
});
Strategy for ServiceWorker
• Cache only
• Network only
• Cache, falling back to network
• Cache & network race
• Network falling back to cache
• Cache then network
• Generic fallback
• ServiceWorker-side templating
Serving suggestions
Performance impact of ServiceWorker
Demo : Trained-to-thrill
• Cache on install, for the static UI and behaviour
• Cache on network response, for the Flickr images and data
• Fetch from cache, falling back to network, for most requests
• Fetch from cache, then network, for the Flickr search results
Demo uses
sw-toolbox
• sw-toolbox is a collection of tools for service workers, create by Google
• Install• npm install --save sw-toolbox
• Register your service worker• navigator.serviceWorker.register('my-service-worker.js’);
• Add Service Worker Toolbox to your service worker script• importScripts('node_components/sw-toolbox/sw-toolbox.js');
sw-toolbox
• toolbox.networkFirst
• toolbox.cacheFirst
• toolbox.fastest
• toolbox.cacheOnly
• toolbox.networkOnly
Handlers
• Router related• toolbox.router.<get|post|put|delete|head>(urlPattern, handler, options)
• toolbox.router.any(urlPattern, handler, options)
• toolbox.router.default
• Cache related• toolbox.precache(arrayOfURLs)
• toolbox.cache(url, options)
• toolbox.uncache(url, options)
Methods
• ResourceCDN(maxEntries: 100, maxAgeSeconds: 1200)• https://<CDNDomain>/Public/*
• ContentCDN(maxEntries: 20, maxAgeSeconds: 1800)• https://<CDNDomain>/ContentCDN/*
• Betgenius(maxEntries: 5, maxAgeSeconds: 600)• https://<BetgeniusDomain>/*
• WebAppLocal(maxEntries: 10, maxAgeSeconds: 1200)• https://<WebAppDomain>/Public/Lib/*
Recommend Setting
Setup Overview
service-worker-init.js
sw-toolbox.js
Site.Master
ResourceCDN
Betgenius
ContentCDN(HomepageCDN)
WebAppLocal
/Public/Lib
• https://<cdn>/Public/JS/Language/en-gb.js?v=07130719
• https://<cdn>/Public/bundles/js/coreJs.js?v=07130719
• https://<cdn>/Public/bundles/js/react.js?v=07130719
• ….
• https://<betgenius>/188BetFlash-phase3/api.js
• https://< betgenius>/188BetFlash-phase3/swfobject.js
• https://<cdn>/ContentCDN/Football/Sport01.jpg?v=143
• https://<cdn>/ContentCDN/Football/Sport02.jpg?v=143
• https://<cdn>/ContentCDN/Football/Sport03.jpg?v=143
• …
• https://<cdn>/Public/Templates/OddsPage/en-gb.Football_AHOU.html?v=07130719
• …
Sample Code Site.Master
Sample Code Service-worker.init.js
Chrome Verification Network Tab
Chrome Verification Application Tab
Result Comparison
Before
After Service-worker First Time Loading
After Service-worker Second time(exclude vendor)
After Service-worker Second time(include vendor)
• React Worker Dom• Github : web-perf/react-worker-dom
• Performance Demo : React Worker Dom
Another optimization from Web Worker
• Service Workers: an Introduction
• Jake Archibald - The offline cookbook
• Making a Simple Site Work Offline with ServiceWorker
References
Q & A
11F., No.399, Ruiguang Rd., Neihu Dist., Taipei City 114, Taiwan
THANK YOU!
Xuenn
+886 2 2798 8529
+886 2 2798 8531
www.xuenn.com
YiTeng
+886 2 2659 8958
+886 2 2659 8956
www.yitmh.com