Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
91 lines (85 loc) · 2.35 KB
/
Copy pathsw.js
File metadata and controls
91 lines (85 loc) · 2.35 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const CACHE_NAME = 'offline-gallery-v01';
const expectedCaches = [CACHE_NAME];
const staticFiles = [
'./',
'./main.css',
'./build/bundle.js',
];
/**
* Performs install steps.
*/
self.addEventListener('install', (event) => {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(staticFiles))
);
});
/**
* Handles requests: responds with cache or else network.
*/
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
event.respondWith(
caches.match(event.request).then(response => response || fetch(event.request))
);
});
/**
* Cleans up static cache and activates the Service Worker.
*/
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(keys => Promise.all(
keys.map((key) => {
if (!expectedCaches.includes(key)) {
return caches.delete(key);
}
})
)).then(() => {
console.log(`${CACHE_NAME} now ready to handle fetches!`);
return clients.claim();
}).then(() => {
return self.clients.matchAll().then(clients =>
Promise.all(clients.map(client =>
client.postMessage('The service worker has activated and taken control. This application can now be used offline.')
))
);
})
);
});
/**
* Listens to messages from the client.
*/
self.addEventListener('message', (event) => {
caches.open('custom').then((cache) => {
switch (event.data.command) {
/**
* Requests asset and add it to the custom cache.
*/
case 'add':
return fetch(new Request(event.data.url, { mode: 'no-cors' }))
.then(response => cache.put(event.data.url, response))
.then(() => {
event.ports[0].postMessage({
error: null,
data: event.data,
count: cache.keys().length,
});
});
/**
* Removes an existing asset from the custom cache.
*/
case 'delete':
return cache.delete(event.data.url).then((success) => {
event.ports[0].postMessage({
error: success ? null : 'Item was not found in the cache.',
count: cache.keys().length,
});
});
/**
* Called event is unknown.
*/
default:
throw Error(`Unknown command: ${event.data.command}`);
}
});
});