1const CACHE_NAME = 'peachjam-offline-v1'; 2const OFFLINE_PAGE = '/offline/offline'; 3 4let isOffline = false; 5 6self.addEventListener('install', (event) => { 7 console.log('Service Worker installing'); 8 self.skipWaiting(); 9}); 10 11self.addEventListener('activate', (event) => { 12 console.log('Service Worker activated'); 13 event.waitUntil( 14 caches.keys().then(keys => 15 Promise.all( 16 keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)) 17 ) 18 ) 19 ); 20 self.clients.claim(); 21}); 22 23self.addEventListener('fetch', (event) => { 24 if (event.request.method !== 'GET') return; 25 26 event.respondWith( 27 // try a normal fetch 28 fetch(event.request) 29 .then(async (response) => { 30 if (event.request.mode === 'navigate' && response.ok && response.type === 'basic' && isOffline) { 31 // we're back online 32 notifyOfflineStatus(false); 33 } 34 return response; 35 }) 36 .catch(async () => { 37 // it failed, try the cache 38 const cache = await caches.open(CACHE_NAME); 39 const response = await cache.match(event.request); 40 41 if (event.request.mode === 'navigate' && !isOffline) { 42 notifyOfflineStatus(true); 43 } 44 45 if (response) { 46 // we found a cached response, return it 47 return response; 48 } 49 50 if (event.request.mode === 'navigate') { 51 // resort to offline page for navigation requests 52 return cache.match(OFFLINE_PAGE); 53 } 54 }) 55 ); 56}); 57 58// respond when the browser wants to determine offline status 59self.addEventListener('message', (event) => { 60 if (event.data?.type === 'requestOfflineStatus') { 61 notifyOfflineStatus(isOffline); 62 } 63}); 64 65function notifyOfflineStatus (offline) { 66 isOffline = offline; 67 self.clients.matchAll({ type: 'window' }).then(clients => { 68 for (const client of clients) { 69 client.postMessage({ type: 'notifyOfflineStatus', value: isOffline }); 70 } 71 }); 72}
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.