From 144bde2d50d71e38ff5aa71d71135d6f4ee01ace Mon Sep 17 00:00:00 2001 From: Michal Vanko Date: Wed, 21 Apr 2021 17:53:39 +0200 Subject: [PATCH] new service worker --- src/service-worker.js | 139 ++++++++++++++++++++++-------------------- 1 file changed, 73 insertions(+), 66 deletions(-) diff --git a/src/service-worker.js b/src/service-worker.js index 2289a55..334dadc 100644 --- a/src/service-worker.js +++ b/src/service-worker.js @@ -1,82 +1,89 @@ -import { timestamp, files, shell, routes } from '@sapper/service-worker'; +import { timestamp, files, shell } from '@sapper/service-worker' -const ASSETS = `cache${timestamp}`; +const ASSETS = `cache${timestamp}` // `shell` is an array of all the files generated by the bundler, // `files` is an array of everything in the `static` directory -const to_cache = shell.concat(files); -const cached = new Set(to_cache); +const to_cache = shell.concat(files) +const staticAssets = new Set(to_cache) -self.addEventListener('install', event => { - event.waitUntil( - caches - .open(ASSETS) - .then(cache => cache.addAll(to_cache)) - .then(() => { - self.skipWaiting(); - }) - ); -}); +self.addEventListener('install', (event) => { + event.waitUntil( + caches + .open(ASSETS) + .then((cache) => cache.addAll(to_cache)) + .then(() => { + self.skipWaiting() + }) + ) +}) -self.addEventListener('activate', event => { - event.waitUntil( - caches.keys().then(async keys => { - // delete old caches - for (const key of keys) { - if (key !== ASSETS) await caches.delete(key); - } +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys().then(async (keys) => { + // delete old caches + for (const key of keys) { + if (key !== ASSETS) await caches.delete(key) + } - self.clients.claim(); - }) - ); -}); + self.clients.claim() + }) + ) +}) -self.addEventListener('fetch', event => { - if (event.request.method !== 'GET' || event.request.headers.has('range')) return; +/** + * Fetch the asset from the network and store it in the cache. + * Fall back to the cache if the user is offline. + */ +async function fetchAndCache(request) { + const cache = await caches.open(`offline${timestamp}`) - const url = new URL(event.request.url); + try { + const response = await fetch(request) + cache.put(request, response.clone()) + return response + } catch (err) { + const response = await cache.match(request) + if (response) return response - // don't try to handle e.g. data: URIs - if (!url.protocol.startsWith('http')) return; + throw err + } +} - // ignore dev server requests - if (url.hostname === self.location.hostname && url.port !== self.location.port) return; +self.addEventListener('fetch', (event) => { + if (event.request.method !== 'GET' || event.request.headers.has('range')) + return - // always serve static files and bundler-generated assets from cache - if (url.host === self.location.host && cached.has(url.pathname)) { - event.respondWith(caches.match(event.request)); - return; - } + const url = new URL(event.request.url) - // for pages, you might want to serve a shell `service-worker-index.html` file, - // which Sapper has generated for you. It's not right for every - // app, but if it's right for yours then uncomment this section - /* - if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) { - event.respondWith(caches.match('/service-worker-index.html')); - return; - } - */ + // don't try to handle e.g. data: URIs + const isHttp = url.protocol.startsWith('http') + const isDevServerRequest = + url.hostname === self.location.hostname && url.port !== self.location.port + const isStaticAsset = + url.host === self.location.host && staticAssets.has(url.pathname) + const skipBecauseUncached = + event.request.cache === 'only-if-cached' && !isStaticAsset - if (event.request.cache === 'only-if-cached') return; + if (isHttp && !isDevServerRequest && !skipBecauseUncached) { + event.respondWith( + (async () => { + // always serve static files and bundler-generated assets from cache. + // if your application has other URLs with data that will never change, + // set this variable to true for them and they will only be fetched once. + const cachedAsset = isStaticAsset && (await caches.match(event.request)) - // for everything else, try the network first, falling back to - // cache if the user is offline. (If the pages never change, you - // might prefer a cache-first approach to a network-first one.) - event.respondWith( - caches - .open(`offline${timestamp}`) - .then(async cache => { - try { - const response = await fetch(event.request); - cache.put(event.request, response.clone()); - return response; - } catch(err) { - const response = await cache.match(event.request); - if (response) return response; - - throw err; + // for pages, you might want to serve a shell `service-worker-index.html` file, + // which Sapper has generated for you. It's not right for every + // app, but if it's right for yours then uncomment this section + /* + if (!cachedAsset && url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) { + return caches.match('/service-worker-index.html'); } - }) - ); -}); + */ + + return cachedAsset || fetchAndCache(event.request) + })() + ) + } +})