victorwesterlund.com/public/sw.js
Victor Westerlund e47a0229f9 Compartmentalized and updated assets
- NETWATCH 404 pages removed - time for something new
- Compartmentalized CSS fonts and JS script files
- Streamlined cache manifest for ServiceWorker
- Added AVIF images, replaced PNG fallback with WebP fallback
- Changed favicon color
2021-06-03 10:59:43 +02:00

102 lines
2.6 KiB
JavaScript

const version = "1622708674";
const root = "/";
let activeCaches = [
`content-${version}`
];
let cacheManifest = [
"index.html",
"assets/css/style.css",
"assets/css/fonts.css",
"assets/img/favicon.png",
"assets/img/pattern.gif",
"assets/fonts/RobotoMono-Bold.woff2",
"assets/fonts/RobotoMono-Regular.woff2",
"assets/js/script.js"
];
// Download assets and install ServiceWorker
self.addEventListener("install", event => {
event.waitUntil(
caches.open(`content-${version}`).then(cache => cache.addAll(cacheManifest.map(asset => {
// Append the root path to all assets
return root + asset;
})))
)
});
// Wipe old assets from Cache Storage
self.addEventListener("activate", event => {
event.waitUntil(
// Delete inactive caches
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if(!activeCaches.includes(cacheName)) {
return caches.delete(cacheName);
}
})
)
})
)
});
// Fetch and cache an asset not defined in the manifest
async function fetchToCache(event) {
const networkFetch = fetch(event.request);
event.waitUntil(
networkFetch.then(response => {
const responseClone = response.clone();
caches.open("bucket").then(cache => cache.put(event.request, responseClone));
})
);
const response = await caches.match(event.request);
return response || networkFetch;
}
// Fetch and follow redirects without caching
async function fetchContent(url,i = 0) {
if(i >= 5) {
throw new Error("ERR_TOO_MANY_REDIRECTS");
}
return await fetch(url).then(response => {
if(response.redirected) {
i++;
return fetchContent(response.url,i);
}
return response;
});
}
self.addEventListener("fetch", event => {
const url = new URL(event.request.url);
const origin = (url.origin == location.origin) ? true : false; // Is same-origin
// Speed up TTFB by serving index file first
if(origin && url.pathname == "/") {
event.respondWith(caches.match(root + "index.html"));
return;
}
// Fetch cross-origin content using the network
if(!origin || (url.pathname.substring(1,7) != "assets")) {
event.respondWith(fetchContent(url.href));
return;
}
// Get pattern.gif from generator. Fallback to cache on failure
if(origin && url.pathname.endsWith("pattern.gif")) {
const pattern = new Request(`${location.origin}${root}assets/img/pattern.php`);
event.respondWith(fetch(pattern).catch(() => caches.match(root + "assets/img/pattern.gif")));
return;
}
// Respond with content from cache or fetch and save
event.respondWith(
caches.match(event.request).then(response => response || fetchToCache(event))
);
});