mirror of
https://github.com/kevin-DL/sapper-template.git
synced 2026-01-12 10:25:16 +00:00
The previous implementation tried to cache only-if-cached by changing request mode but it doesn't work because the property is readonly. However, caching responses cached with HTTP Cache again with Cache API does not make sense anyway. Just do not cache it, and leave it to HTTP cache.
83 lines
2.2 KiB
JavaScript
83 lines
2.2 KiB
JavaScript
import { timestamp, assets, shell, routes } from './manifest/service-worker.js';
|
|
|
|
const ASSETS = `cache${timestamp}`;
|
|
|
|
// `shell` is an array of all the files generated by webpack,
|
|
// `assets` is an array of everything in the `assets` directory
|
|
const to_cache = shell.concat(assets);
|
|
const cached = new Set(to_cache);
|
|
|
|
self.addEventListener('install', event => {
|
|
event.waitUntil(
|
|
caches
|
|
.open(ASSETS)
|
|
.then(cache => cache.addAll(to_cache))
|
|
.then(() => {
|
|
self.skipWaiting();
|
|
})
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', event => {
|
|
event.waitUntil(
|
|
caches.keys().then(async keys => {
|
|
// delete old caches
|
|
for (const key of keys) {
|
|
if (key !== ASSETS) await caches.delete(key);
|
|
}
|
|
|
|
self.clients.claim();
|
|
})
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', event => {
|
|
if (event.request.method !== 'GET') return;
|
|
|
|
const url = new URL(event.request.url);
|
|
|
|
// don't try to handle e.g. data: URIs
|
|
if (!url.protocol.startsWith('http')) return;
|
|
|
|
// ignore dev server requests
|
|
if (url.hostname === self.location.hostname && url.port !== self.location.port) return;
|
|
|
|
// always serve assets and webpack-generated files from cache
|
|
if (url.host === self.location.host && cached.has(url.pathname)) {
|
|
event.respondWith(caches.match(event.request));
|
|
return;
|
|
}
|
|
|
|
// for pages, you might want to serve a shell `index.html` file,
|
|
// which Sapper has generated for you. It's not right for every
|
|
// app, but if it's right for yours then uncomment this section
|
|
/*
|
|
if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
|
|
event.respondWith(caches.match('/index.html'));
|
|
return;
|
|
}
|
|
*/
|
|
|
|
if (event.request.cache === 'only-if-cached') return;
|
|
|
|
// for everything else, try the network first, falling back to
|
|
// cache if the user is offline. (If the pages never change, you
|
|
// might prefer a cache-first approach to a network-first one.)
|
|
event.respondWith(
|
|
caches
|
|
.open(`offline${timestamp}`)
|
|
.then(async cache => {
|
|
try {
|
|
const response = await fetch(event.request);
|
|
cache.put(event.request, response.clone());
|
|
return response;
|
|
} catch(err) {
|
|
const response = await cache.match(event.request);
|
|
if (response) return response;
|
|
|
|
throw err;
|
|
}
|
|
})
|
|
);
|
|
});
|