|
| 1 | +const CACHE_NAME = 'slr-cache-v1'; |
| 2 | + |
| 3 | +// Assets to cache immediately |
| 4 | +const PRECACHE_ASSETS = [ |
| 5 | + '/', |
| 6 | + '/manifest.webmanifest', |
| 7 | + '/icon-192.png', |
| 8 | + '/icon-512.png', |
| 9 | +]; |
| 10 | + |
| 11 | +self.addEventListener('install', (event) => { |
| 12 | + event.waitUntil( |
| 13 | + caches.open(CACHE_NAME).then((cache) => { |
| 14 | + return cache.addAll(PRECACHE_ASSETS); |
| 15 | + }) |
| 16 | + ); |
| 17 | + self.skipWaiting(); |
| 18 | +}); |
| 19 | + |
| 20 | +self.addEventListener('activate', (event) => { |
| 21 | + event.waitUntil( |
| 22 | + caches.keys().then((cacheNames) => { |
| 23 | + return Promise.all( |
| 24 | + cacheNames.map((cacheName) => { |
| 25 | + if (cacheName !== CACHE_NAME) { |
| 26 | + return caches.delete(cacheName); |
| 27 | + } |
| 28 | + }) |
| 29 | + ); |
| 30 | + }) |
| 31 | + ); |
| 32 | + self.clients.claim(); |
| 33 | +}); |
| 34 | + |
| 35 | +self.addEventListener('fetch', (event) => { |
| 36 | + // Skip cross-origin requests (like Clerk or Neon) |
| 37 | + if (!event.request.url.startsWith(self.location.origin)) return; |
| 38 | + |
| 39 | + // Stale-while-revalidate strategy |
| 40 | + event.respondWith( |
| 41 | + caches.open(CACHE_NAME).then((cache) => { |
| 42 | + return cache.match(event.request).then((response) => { |
| 43 | + const fetchPromise = fetch(event.request).then((networkResponse) => { |
| 44 | + // Cache the new response if it's a valid GET request |
| 45 | + if (event.request.method === 'GET' && networkResponse.status === 200) { |
| 46 | + cache.put(event.request, networkResponse.clone()); |
| 47 | + } |
| 48 | + return networkResponse; |
| 49 | + }); |
| 50 | + return response || fetchPromise; |
| 51 | + }); |
| 52 | + }) |
| 53 | + ); |
| 54 | +}); |
0 commit comments