2022-01-01 23:10:41 +08:00
|
|
|
const staticCacheName = "sw-cache";
|
|
|
|
|
|
|
|
self.addEventListener("install", (event) => {
|
2021-12-14 01:46:51 +08:00
|
|
|
event.waitUntil(
|
2022-01-01 23:10:41 +08:00
|
|
|
caches.open(staticCacheName).then((cache) => {
|
|
|
|
// Cache the base file(s)
|
|
|
|
return cache.add("/");
|
2021-12-14 01:46:51 +08:00
|
|
|
})
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
2022-01-01 23:10:41 +08:00
|
|
|
self.addEventListener("fetch", async (event) => {
|
|
|
|
const host = new URL(event.request.url).host;
|
|
|
|
if (
|
2022-01-03 20:23:37 +08:00
|
|
|
[
|
|
|
|
"localhost:5005",
|
|
|
|
"api.monkeytype.com",
|
|
|
|
"api.github.com",
|
|
|
|
"www.google-analytics.com",
|
|
|
|
].includes(host) ||
|
|
|
|
host.endsWith("wikipedia.org")
|
2022-01-01 23:10:41 +08:00
|
|
|
) {
|
|
|
|
// if hostname is a non-static api, fetch request
|
|
|
|
event.respondWith(fetch(event.request));
|
|
|
|
} else {
|
|
|
|
// Otherwise, assume host is serving a static file, check cache and add response to cache if not found
|
|
|
|
event.respondWith(
|
|
|
|
caches.match(event.request).then(async (response) => {
|
|
|
|
// Check if request in cache
|
|
|
|
if (response) {
|
|
|
|
// if response was found in the cache, send from cache
|
|
|
|
return response;
|
|
|
|
} else {
|
|
|
|
// if response was not found in cache fetch from server, cache it and send it
|
|
|
|
response = await fetch(event.request);
|
|
|
|
return caches.open(staticCacheName).then((cache) => {
|
|
|
|
cache.put(event.request.url, response.clone());
|
|
|
|
return response;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
2021-12-14 01:46:51 +08:00
|
|
|
});
|