leanwebclub/structure-and-scale/seven-seas-cache-strategy/sw.js

77 lines
1.8 KiB
JavaScript

/** I found this MDN page to be a good reference for service workers.
*
* https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers
*
**/
let coreAssets = [
'public/css/style.css',
'public/js/index.js',
'public/js/treasure.js',
'public/js/dice.js',
'offline.html',
'index.html',
'treasure.html',
'dice.html'
];
async function addResourcesToCache (assets) {
const cache = await caches.open('app');
for (let asset of assets) {
await cache.add(new Request(asset));
}
return cache;
}
async function offlineFirst (event) {
return await caches.match(event.request) || await fetch(event.request);
}
async function networkFirst (event) {
let response;
try {
response = await fetch(event.request) || await caches.match(event.request);
} catch (error) {
response = await caches.match('offline.html');
}
return response
}
// Listen for the install event
self.addEventListener('install', function (event) {
// Activate immediately
self.skipWaiting();
// Cache core assets
event.waitUntil(addResourcesToCache(coreAssets));
});
// Listen for request events
self.addEventListener('fetch', function (event) {
// Get the request
let request = event.request;
// Bug fix
// https://stackoverflow.com/a/49719964
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') return;
// HTML files
// Network-first
if (request.headers.get('Accept').includes('text/html')) {
event.respondWith(networkFirst(event));
}
// Check the cache first
// If it's not found, send the request to the network
if (request.headers.get('Accept').includes('text/css') || request.headers.get('Accept').includes('text/javascript')) {
event.respondWith(offlineFirst(event));
}
});