-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathsw.js
72 lines (65 loc) · 1.92 KB
/
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
// Cache store name to save static resources
const CACHE_STATIC = 'static-cache-v1';
// Minimal set of files to cache to be a PWA
const FILES_TO_CACHE = [
'./',
'./favicon.ico',
'./img/favicon-512.png',
'./index.html',
'./pwa.json',
];
// FUNCS
/**
* When a service worker is initially registered, pages won't use it until they next load. The claim() method causes
* those pages to be controlled immediately.
*
* @param {ExtendableEvent} evt
*/
function onActivate(evt) {
console.log(`SW: send 'claim' message to the clients.`);
evt.waitUntil(
self.clients.claim()
);
}
/**
* Return static resource from cache (if exists) or fetch from network.
* @param {FetchEvent} evt
*/
function onFetch(evt) {
// FUNCS
async function cacheOrFetch(req) {
const cache = await self.caches.open(CACHE_STATIC);
const cachedResponse = await cache.match(req);
return cachedResponse ?? await fetch(req);
}
// MAIN
console.log(`SW: fetch '${evt.request}'.`);
evt.respondWith(cacheOrFetch(evt.request));
}
/**
* Load and store required static resources on installation.
* @param {ExtendableEvent} evt
*/
function onInstall(evt) {
// FUNCS
async function cacheStaticFiles() {
const cacheStat = await caches.open(CACHE_STATIC);
// load all resources at the same time (parallel)
await Promise.all(
FILES_TO_CACHE.map(function (url) {
return cacheStat.add(url).catch(function (reason) {
console.log(`'${url}' failed: ${String(reason)}`);
});
})
);
}
// MAIN
console.log(`SW: cache app shell on install.`);
// wait until all static files will be cached
evt.waitUntil(cacheStaticFiles());
}
// MAIN
self.addEventListener('activate', onActivate);
self.addEventListener('fetch', onFetch);
self.addEventListener('install', onInstall);