Maxim Salnikov
@webmaxru
How to improve a web app performance and UX
Developer Audience Lead at Microsoft
Service worker
Networking
Caching
Installability
Capabilities
self.addEventListener('install', event => {
// Putting resources into the Cache Storage
})
self.addEventListener('activate', event => {
// Managing versions
})
self.addEventListener('fetch', event => {
// Exctracting from the cache and serving
})
const PRECACHE = 'precache-v1';
const RUNTIME = 'runtime';
const PRECACHE_URLS = [
'index.html',
'./',
'styles.css',
'../../styles/main.css',
'demo.js'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(PRECACHE)
.then(cache => cache.addAll(PRECACHE_URLS))
.then(self.skipWaiting())
);
});
self.addEventListener('activate', event => {
const currentCaches = [PRECACHE, RUNTIME];
event.waitUntil(
caches.keys().then(cacheNames => {
return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
}).then(cachesToDelete => {
return Promise.all(cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
}));
}).then(() => self.clients.claim())
);
});
self.addEventListener('fetch', event => {
if (event.request.url.startsWith(self.location.origin)) {
if (event.request.url.indexOf('api/') != -1) {
event.respondWith(
caches.match(event.request.clone()).then((response) => {
return response || fetch(event.request.clone()).then((r2) => {
return caches.open(RUNTIME).then((cache) => {
cache.put(event.request.url, r2.clone());
return r2.clone();
});
});
})
);
} else {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
return caches.open(RUNTIME).then(cache => {
return fetch(event.request).then(response => {
return cache.put(event.request, response.clone()).then(() => {
return response;
});
});
});
})
);
}
}
});
import { precacheAndRoute } from "workbox-precaching";
// Cache and serve resources from __WB_MANIFEST array
precacheAndRoute(self.__WB_MANIFEST);
# Using Workbox as a Node module
$ npm install workbox-build
On every app build
const { injectManifest } = require("workbox-build");
let workboxConfig = {
swSrc: "src/service-worker.js",
swDest: "dist/sw.js",
globPatterns: ["index.html", "*.css", "*.js"]
};
injectManifest(workboxConfig).then(() => {
console.log(`Generated ${workboxConfig.swDest}`);
});
import { precacheAndRoute } from "workbox-precaching";
precacheAndRoute([
{ revision: "866bcc582589b8920dbc", url: "index.html" },
{ revision: "c2761edff7776e1e48a3", url: "styles.css" },
{ revision: "3469613435532733abd9", url: "main.js" }
]);
import { precacheAndRoute } from "workbox-precaching";
precacheAndRoute(self.__WB_MANIFEST);
import resolve from 'rollup-plugin-node-resolve'
import replace from 'rollup-plugin-replace'
import { terser } from 'rollup-plugin-terser'
export default {
input: 'dist/sw.js',
output: {
file: 'dist/sw.js',
format: 'iife'
},
plugins: [ /* On the next slide */ ]
}
plugins: [
resolve(),
replace({
'process.env.NODE_ENV': JSON.stringify('production')
}),
terser()
]
"build-pwa":
"npm run build-app &&
node build-sw.js &&
npx rollup -c"
import { Workbox, messageSW } from 'workbox-window';
if ('serviceWorker' in navigator) {
const wb = new Workbox('/sw.js');
wb.register();
// Interactive update flow with messageSW
// code sample is at https://aka.ms/workbox6
}
New version is available. Click to reload.
Works offline (application shell)
Managing versions
Detailed debug information
import { registerRoute } from "workbox-routing";
import {
CacheFirst,
NetworkFirst,
StaleWhileRevalidate,
} from "workbox-strategies";
// Avatars can always be taken from the cache
registerRoute(
new RegExp("https://www.gravatar.com/avatar/.*"),
new CacheFirst()
);
// Keeping article list always fresh
registerRoute(
({url}) => url.pathname.startsWith('/api/articles/'),
new NetworkFirst()
);
// Retrieving article from the cache and checking for updates
import { BroadcastUpdatePlugin } from 'workbox-broadcast-update';
registerRoute(
({url}) => url.pathname.startsWith('/api/article/'),
new StaleWhileRevalidate({
plugins: [
new BroadcastUpdatePlugin()
],
})
);
import {
googleFontsCache,
imageCache
} from "workbox-recipes";
// Caching Google Fonts
googleFontsCache({ cachePrefix: "wb6-gfonts" });
// Caching images
imageCache({ maxEntries: 10 });
// Pages and images fallback
offlineFallback();
// Pages caching
pageCache();
// Static assets caching
staticResourceCache();
// Cache warming up
warmStrategyCache(urls, strategy);
Service worker generation using CLI
Custom strategies
import {Strategy} from 'workbox-strategies';
class CacheNetworkRace extends Strategy {
async _handle(request, handler /* StrategyHandler ins. */) {
// Requesting, processing, returning results
}
}
_handle(request, handler) {
const fetchDone = handler.fetchAndCachePut(request);
const matchDone = handler.cacheMatch(request);
return new Promise((resolve, reject) => {
fetchDone.then(resolve);
matchDone.then((response) => response && resolve(response));
Promise.allSettled([fetchDone, matchDone]).then(/* reject */)
});
}