From c048011b07fe531a23eb70c09342cd011fe059f4 Mon Sep 17 00:00:00 2001 From: Tusooa Zhu Date: Thu, 12 Aug 2021 22:42:08 -0400 Subject: [PATCH] Cache compiled assets in service worker --- src/sw.js | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/sw.js b/src/sw.js index cc419f74..23a63c38 100644 --- a/src/sw.js +++ b/src/sw.js @@ -49,6 +49,35 @@ const maybeShowNotification = async (event) => { } } +const shouldCache = process.env.NODE_ENV === 'production' +const cacheKey = 'pleroma-fe' +const cacheFiles = self.serviceWorkerOption.assets + +self.addEventListener('install', async (event) => { + if (shouldCache) { + event.waitUntil((async () => { + const cache = await caches.open(cacheKey) + await cache.addAll(cacheFiles) + })()) + } +}) + +self.addEventListener('activate', async (event) => { + if (shouldCache) { + event.waitUntil((async () => { + const cache = await caches.open(cacheKey) + const keys = await cache.keys() + await Promise.all( + keys.filter(request => { + const url = new URL(request.url) + const shouldKeep = cacheFiles.includes(url.pathname) + return !shouldKeep + }).map(k => cache.delete(k)) + ) + })()) + } +}) + self.addEventListener('push', async (event) => { if (event.data) { event.waitUntil(maybeShowNotification(event)) @@ -68,4 +97,16 @@ self.addEventListener('notificationclick', (event) => { })) }) -self.addEventListener('fetch', _ => _) +self.addEventListener('fetch', async (event) => { + if (shouldCache) { + event.respondWith((async () => { + const r = await caches.match(event.request) + console.log(`[Service Worker] Fetching resource: ${event.request.url}`) + if (r) { + return r + } + const response = await fetch(event.request) + return response + })()) + } +})