|
| 1 | +const version = "v1.3"; |
| 2 | + |
| 3 | +const addResourcesToCache = async (resources) => { |
| 4 | + const cache = await caches.open(version); |
| 5 | + console.log("Adding resources to cache:", resources.join(", ")); |
| 6 | + await cache.addAll(resources); |
| 7 | +}; |
| 8 | + |
| 9 | +const putInCache = async (request, response) => { |
| 10 | + const cache = await caches.open(version); |
| 11 | + await cache.put(request, response); |
| 12 | +}; |
| 13 | + |
| 14 | +const networkFirst = async ({ request, fallbackUrl }) => { |
| 15 | + // First, try to get the resource from the network. |
| 16 | + try { |
| 17 | + const responseFromNetwork = await fetch(request); |
| 18 | + // If the network request succeeded, clone the response: |
| 19 | + // - put one copy in the cache, for the next time |
| 20 | + // - return the original to the app |
| 21 | + // Cloning is needed because a response can only be consumed once. |
| 22 | + putInCache(request, responseFromNetwork.clone()); |
| 23 | + return responseFromNetwork; |
| 24 | + } catch (error) { |
| 25 | + const responseFromCache = await caches.match(request); |
| 26 | + if (responseFromCache) { |
| 27 | + return responseFromCache; |
| 28 | + } |
| 29 | + |
| 30 | + const fallbackResponse = await caches.match(fallbackUrl); |
| 31 | + if (fallbackResponse) { |
| 32 | + return fallbackResponse; |
| 33 | + } |
| 34 | + // When even the fallback response is not available, |
| 35 | + // there is nothing we can do, but we must always |
| 36 | + // return a Response object. |
| 37 | + return new Response("Network error happened", { |
| 38 | + status: 408, |
| 39 | + headers: { "Content-Type": "text/plain" }, |
| 40 | + }); |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +self.addEventListener("fetch", (event) => { |
| 45 | + event.respondWith( |
| 46 | + networkFirst({ |
| 47 | + request: event.request, |
| 48 | + fallbackUrl: "/fallback.html", |
| 49 | + }), |
| 50 | + ); |
| 51 | +}); |
| 52 | + |
| 53 | +self.addEventListener("install", (event) => { |
| 54 | + event.waitUntil( |
| 55 | + addResourcesToCache([ |
| 56 | + "/", |
| 57 | + "/index.html", |
| 58 | + "/index.css", |
| 59 | + "/css/webfonts_Chess", |
| 60 | + "/css/hex.css", |
| 61 | + "/css/print.css", |
| 62 | + "/js/black.js", |
| 63 | + "/js/board.js", |
| 64 | + "/js/constants.js", |
| 65 | + "/js/play.js", |
| 66 | + "/js/register.js", |
| 67 | + "/js/white.js", |
| 68 | + ]), |
| 69 | + ); |
| 70 | +}); |
0 commit comments