|
| 1 | +const CACHE_NAME = 'pushy-site-v1'; |
| 2 | +const PRECACHE_URLS = ['/', '/manifest.webmanifest', '/images/logo.svg']; |
| 3 | + |
| 4 | +self.addEventListener('install', (event) => { |
| 5 | + event.waitUntil( |
| 6 | + caches |
| 7 | + .open(CACHE_NAME) |
| 8 | + .then((cache) => cache.addAll(PRECACHE_URLS)) |
| 9 | + .then(() => self.skipWaiting()), |
| 10 | + ); |
| 11 | +}); |
| 12 | + |
| 13 | +self.addEventListener('activate', (event) => { |
| 14 | + event.waitUntil( |
| 15 | + caches |
| 16 | + .keys() |
| 17 | + .then((keys) => |
| 18 | + Promise.all( |
| 19 | + keys |
| 20 | + .filter((key) => key !== CACHE_NAME) |
| 21 | + .map((key) => caches.delete(key)), |
| 22 | + ), |
| 23 | + ) |
| 24 | + .then(() => self.clients.claim()), |
| 25 | + ); |
| 26 | +}); |
| 27 | + |
| 28 | +self.addEventListener('fetch', (event) => { |
| 29 | + const { request } = event; |
| 30 | + |
| 31 | + if (request.method !== 'GET') { |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + const url = new URL(request.url); |
| 36 | + if (url.origin !== self.location.origin) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + if (request.mode === 'navigate') { |
| 41 | + event.respondWith( |
| 42 | + fetch(request) |
| 43 | + .then((response) => { |
| 44 | + const copy = response.clone(); |
| 45 | + caches.open(CACHE_NAME).then((cache) => cache.put(request, copy)); |
| 46 | + return response; |
| 47 | + }) |
| 48 | + .catch(() => caches.match(request).then((cached) => cached || caches.match('/'))), |
| 49 | + ); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + event.respondWith( |
| 54 | + caches.match(request).then((cached) => { |
| 55 | + if (cached) { |
| 56 | + return cached; |
| 57 | + } |
| 58 | + |
| 59 | + return fetch(request).then((response) => { |
| 60 | + if (response.ok) { |
| 61 | + const copy = response.clone(); |
| 62 | + caches.open(CACHE_NAME).then((cache) => cache.put(request, copy)); |
| 63 | + } |
| 64 | + return response; |
| 65 | + }); |
| 66 | + }), |
| 67 | + ); |
| 68 | +}); |
0 commit comments