From b84caadaae84c4fcb82585110bcddbf20448e660 Mon Sep 17 00:00:00 2001 From: Dan Cojocaru Date: Sun, 14 Aug 2022 13:12:14 +0200 Subject: [PATCH] Added service worker --- about.html | 3 +- index.html | 1 + sw.js | 116 ++++++++++++++++++++++++++++++++++++++++++++++++ train.html | 1 + view-train.html | 1 + worker.js | 23 ++++++++++ 6 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 sw.js create mode 100644 worker.js diff --git a/about.html b/about.html index 296fa37..a082d52 100644 --- a/about.html +++ b/about.html @@ -8,6 +8,7 @@ + @@ -30,4 +31,4 @@
- \ No newline at end of file + diff --git a/index.html b/index.html index a0c33c2..7ca1db3 100644 --- a/index.html +++ b/index.html @@ -10,6 +10,7 @@ + diff --git a/sw.js b/sw.js new file mode 100644 index 0000000..2741ea8 --- /dev/null +++ b/sw.js @@ -0,0 +1,116 @@ +const VERSION = 'v1' +const API_ORIGIN = 'https://scraper.infotren.dcdev.ro/' +const API_TRAINS = `${API_ORIGIN}v2/trains` +const API_STATIONS = `${API_ORIGIN}v2/stations` + +self.addEventListener('install', (event) => { + event.waitUntil( + caches + .open(VERSION) + .then((cache) => + cache.addAll([ + // Root + '/', + + // Utility JS + '/worker.js', + '/items.js', + '/back.js', + + // Base + '/base.css', + + // Pages + '/index.html', + + '/about.html', + + '/train.html', + '/train.js', + + '/view-train.html', + '/view-train.js', + '/view-train.css', + + // API + API_TRAINS, + API_STATIONS, + + ]) + ) + ) +}) + +const deleteCache = (key) => caches.delete(key) + +const deleteOldCaches = async () => { + const cacheKeepList = [VERSION] + const keyList = await caches.keys() + const cachesToDelete = keyList.filter((key) => !cacheKeepList.includes(key)) + await Promise.all(cachesToDelete.map(deleteCache)) +} + +self.addEventListener('activate', (event) => { + event.waitUntil(deleteOldCaches()) +}) + +// Enable navigation preload +const enableNavigationPreload = async () => { + if (self.registration.navigationPreload) { + // Enable navigation preloads! + await self.registration.navigationPreload.enable() + } +} + +const putInCache = async (request, response) => { + const cache = await caches.open(VERSION) + await cache.put(request, response) +} + +const cacheFirst = async ({ request, preloadResponsePromise, refreshAnyway }) => { + // First try to get the resource from the cache + const responseFromCache = await caches.match(request) + if (responseFromCache) { + if (refreshAnyway) { + console.log('request in cache, refreshing anyway but returning cache', request); + ((async () => { + try { + const response = await fetch(request) + if (response.ok) { + putInCache(request, response) + } + } + catch {} + })()) + } + return responseFromCache + } + + // Next try to use (and cache) the preloaded response, if it's there + const preloadResponse = await preloadResponsePromise + if (preloadResponse) { + console.info('using preload response', preloadResponse) + putInCache(request, preloadResponse.clone()) + return preloadResponse + } + + // Next try to get the resource from the network + const responseFromNetwork = await fetch(request) + // response may be used only once + // we need to save clone to put one copy in cache + // and serve second one + if (responseFromNetwork.ok) { + putInCache(request, responseFromNetwork.clone()) + } + return responseFromNetwork; +} + +self.addEventListener('fetch', (event) => { + event.respondWith( + cacheFirst({ + request: event.request, + preloadResponsePromise: event.preloadResponse, + refreshAnyway: [API_STATIONS, API_TRAINS].includes(event.request.url), + }) + ) +}) diff --git a/train.html b/train.html index a2b69e5..db9db2f 100644 --- a/train.html +++ b/train.html @@ -10,6 +10,7 @@ + diff --git a/view-train.html b/view-train.html index 2a5f3d1..dc0cc52 100644 --- a/view-train.html +++ b/view-train.html @@ -11,6 +11,7 @@ + diff --git a/worker.js b/worker.js new file mode 100644 index 0000000..882fb19 --- /dev/null +++ b/worker.js @@ -0,0 +1,23 @@ +const registerServiceWorker = async () => { + if ('serviceWorker' in navigator) { + try { + const registration = await navigator.serviceWorker.register( + '/sw.js', + { + scope: '/', + } + ); + if (registration.installing) { + console.log('Service worker installing'); + } else if (registration.waiting) { + console.log('Service worker installed'); + } else if (registration.active) { + console.log('Service worker active'); + } + } catch (error) { + console.error(`Registration failed with ${error}`); + } + } +}; + +registerServiceWorker();