|
| 1 | +const IMAGE_CACHE = 'images-v1'; |
| 2 | + |
| 3 | +const DAY = 1000 * 60 * 60 * 24; |
| 4 | + |
| 5 | +let imageToElementMap = {}; |
| 6 | + |
| 7 | +// Install event - precache critical images |
| 8 | +self.addEventListener('install', event => { |
| 9 | + event.waitUntil( |
| 10 | + caches.open(IMAGE_CACHE).then(async (cache) => { |
| 11 | + // Fetch the manifest |
| 12 | + const manifestResponse = await fetch('/manifest.json'); |
| 13 | + const manifest = await manifestResponse.json(); |
| 14 | + |
| 15 | + // Extract asset URLs from manifest |
| 16 | + const assetUrls = Object.values(manifest) |
| 17 | + .filter(entry => entry.file && entry.file.match(/\.(png|jpg|jpeg|svg|webp)$/)) |
| 18 | + .map(entry => `/${entry.file}`); |
| 19 | + |
| 20 | + const uniqueAssetUrls = [...new Set(assetUrls)]; |
| 21 | + |
| 22 | + return cache.addAll(uniqueAssetUrls); |
| 23 | + }).catch((e => { |
| 24 | + console.error('Error prefetching cached images: ', e); |
| 25 | + })) |
| 26 | + ); |
| 27 | +}); |
| 28 | + |
| 29 | + |
| 30 | +self.addEventListener('activate', event => { |
| 31 | + console.log('V1 now ready to handle fetches!'); |
| 32 | +}); |
| 33 | + |
| 34 | +// Fetch event - intercept image requests |
| 35 | +self.addEventListener('fetch', (event) => { |
| 36 | + const url = new URL(event.request.url); |
| 37 | + const isLocal = url.origin === location.origin; |
| 38 | + |
| 39 | + if (event.request.destination === 'image') { |
| 40 | + |
| 41 | + event.respondWith( |
| 42 | + caches.open(IMAGE_CACHE).then(cache => { |
| 43 | + return cache.match(event.request).then(response => { |
| 44 | + if (response) { |
| 45 | + return response; |
| 46 | + } |
| 47 | + |
| 48 | + if (isLocal) { |
| 49 | + // Fetch fresh image |
| 50 | + return fetch(event.request).then(fetchResponse => { |
| 51 | + cache.put(event.request, fetchResponse.clone()); |
| 52 | + return fetchResponse; |
| 53 | + }).catch(error => { |
| 54 | + console.error('FAILED TO FETCH IMAGE: ', url); |
| 55 | + }); |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | + return fetch(event.request).then(fetchResponse => { |
| 60 | + return fetchResponse; |
| 61 | + }).catch(error => { |
| 62 | + console.error('FAILED TO FETCH IMAGE: ', url); |
| 63 | + }); |
| 64 | + }); |
| 65 | + }) |
| 66 | + ); |
| 67 | + } |
| 68 | +}); |
| 69 | + |
| 70 | +self.addEventListener('message', event => { |
| 71 | + if (event.data.type === 'CACHE_AVATAR' && typeof event.data.url === 'string') { |
| 72 | + const url = event.data.url; |
| 73 | + |
| 74 | + event.waitUntil( |
| 75 | + caches.open(IMAGE_CACHE).then(cache => { |
| 76 | + return cache.add(url); |
| 77 | + }).catch((e) => { |
| 78 | + console.log('FAILED TO CACHE AVATAR: ', url) |
| 79 | + }) |
| 80 | + ) |
| 81 | + } |
| 82 | +}); |
0 commit comments