diff --git a/public/service-worker.js b/public/service-worker.js new file mode 100644 index 0000000..1b32577 --- /dev/null +++ b/public/service-worker.js @@ -0,0 +1,66 @@ +// service-worker.js +const CACHE_NAME = 'nvAux-cache'; +const urlsToCache = [ + '/', + '/index.html', + '/favicon.png', +]; + +self.addEventListener('install', (event) => { + // Perform install steps + event.waitUntil( + caches.open(CACHE_NAME) + .then((cache) => { + console.log('Opened cache'); + return cache.addAll(urlsToCache); + }) + ); +}); + +self.addEventListener('fetch', (event) => { + event.respondWith( + caches.match(event.request) + .then((response) => { + // Cache hit - return response + if (response) { + return response; + } + return fetch(event.request).then( + (response) => { + // Check if we received a valid response + if (!response || response.status !== 200 || response.type !== 'basic') { + return response; + } + + // IMPORTANT: Clone the response. A response is a stream + // and because we want the browser to consume the response + // as well as the cache consuming the response, we need + // to clone it so we have two streams. + const responseToCache = response.clone(); + + caches.open(CACHE_NAME) + .then((cache) => { + cache.put(event.request, responseToCache); + }); + + return response; + } + ); + }) + ); +}); + +self.addEventListener('activate', (event) => { + const cacheWhitelist = [CACHE_NAME]; + event.waitUntil( + caches.keys().then((cacheNames) => { + return Promise.all( + cacheNames.map((cacheName) => { + if (cacheWhitelist.indexOf(cacheName) === -1) { + return caches.delete(cacheName); + } + }) + ); + }) + ); +}); diff --git a/src/App.svelte b/src/App.svelte index 10b5aff..9398730 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -1,4 +1,6 @@