| 1 |
/** |
| 2 |
* SPDX-FileCopyrightText: 2020 Carson Black <[email protected]> |
| 3 |
* |
| 4 |
* SPDX-License-Identifier: BSD-2-Clause |
| 5 |
*/ |
| 6 |
|
| 7 |
const ServiceWorkerVersion = 0 |
| 8 |
const AssetCacheName = `assets-${ServiceWorkerVersion}` |
| 9 |
|
| 10 |
self.addEventListener("install", event => { |
| 11 |
event.waitUntil( |
| 12 |
caches.open(AssetCacheName).then(cache => { |
| 13 |
return cache.addAll([ |
| 14 |
"/resources", |
| 15 |
"/index.html", |
| 16 |
]) |
| 17 |
}) |
| 18 |
) |
| 19 |
}) |
| 20 |
|
| 21 |
self.addEventListener("activate", event => { |
| 22 |
event.waitUntil( |
| 23 |
caches.keys().then(cacheNames => { |
| 24 |
return Promise.all( |
| 25 |
cacheNames.map(cacheName => { |
| 26 |
if (cacheName != AssetCacheName) { |
| 27 |
return caches.delete(cacheName) |
| 28 |
} |
| 29 |
}) |
| 30 |
) |
| 31 |
}) |
| 32 |
) |
| 33 |
}) |
| 34 |
|
| 35 |
self.addEventListener("fetch", event => { |
| 36 |
event.respondWith( |
| 37 |
caches.open(AssetCacheName).then(cache => { |
| 38 |
return cache.match(event.request).then(response => { |
| 39 |
if (response) { |
| 40 |
return response |
| 41 |
} |
| 42 |
|
| 43 |
return fetch(event.request.clone()).then(requestResponse => { |
| 44 |
if (requestResponse.status < 400) { |
| 45 |
cache.put(event.request, requestResponse.clone()) |
| 46 |
} |
| 47 |
|
| 48 |
return requestResponse |
| 49 |
}) |
| 50 |
}, error => { |
| 51 |
console.log(`Error in cache match: ${error}`) |
| 52 |
throw error |
| 53 |
}) |
| 54 |
}, error => { |
| 55 |
console.log(`Error in cache opening: ${error}`) |
| 56 |
throw error |
| 57 |
}) |
| 58 |
) |
| 59 |
}) |
| 60 |
|
| 61 |
self.addEventListener("message", (ev) => { |
| 62 |
if (ev.data && ev.data.type === "CONSIDER_CACHING") { |
| 63 |
let url = ev.data.url |
| 64 |
if (url.includes('/html/')) { |
| 65 |
let toCache = url.split('/html/')[0] |
| 66 |
caches.open(AssetCacheName).then(cache => { |
| 67 |
return cache.addAll([ |
| 68 |
toCache |
| 69 |
]) |
| 70 |
}) |
| 71 |
} |
| 72 |
} |
| 73 |
}) |