diff options
| author | Alexis Hovorka <[email protected]> | 2021-07-04 23:07:40 -0600 | 
|---|---|---|
| committer | Alexis Hovorka <[email protected]> | 2021-07-04 23:07:40 -0600 | 
| commit | 1d3dfb9b02f400ec4ce2f6dd2ae8301069aea6b1 (patch) | |
| tree | 3e1eca3620cd8bb71d402111f247e3adabfeeb83 /sw1.js | |
Diffstat (limited to 'sw1.js')
| -rw-r--r-- | sw1.js | 29 | 
1 files changed, 29 insertions, 0 deletions
| @@ -0,0 +1,29 @@ +// https://gist.github.com/adactio/3717b7da007a9363ddf21f584aae34af + +// HTML files: try the network first, then the cache. +// Other files: try the cache first, then the network. +// Both: cache a fresh version if possible. +// (beware: the cache will grow and grow; there's no cleanup) + +const cacheName = "appname-files"; + +addEventListener("fetch", fetchEvent => { +  const request = fetchEvent.request; +  if (request.method !== "GET") return; +  fetchEvent.respondWith(async () => { +    const fetchPromise = fetch(request); +    fetchEvent.waitUntil(async () => { +      const responseFromFetch = await fetchPromise; +      const responseCopy = responseFromFetch.clone(); +      const myCache = await caches.open(cacheName); +      return myCache.put(request, responseCopy); +    }()); +    if (request.headers.get("Accept").includes("text/html")) { +      try { return await fetchPromise; } +      catch(error) { return caches.match(request); } +    } else { +      const responseFromCache = await caches.match(request); +      return responseFromCache || fetchPromise; +    } +  }()); +}); | 
