93 lines
2.4 KiB
JavaScript
93 lines
2.4 KiB
JavaScript
let CACHE_STATIC_NAME = "static-v2";
|
|
let CACHE_DYNAMIC_NAME = "dynamic-v3";
|
|
|
|
self.addEventListener("install", function (event) {
|
|
console.log("[SW install]", event);
|
|
self.skipWaiting();
|
|
event.waitUntil(
|
|
caches.open(CACHE_STATIC_NAME).then((cache) => {
|
|
console.log("[SW precache]");
|
|
return cache.addAll([
|
|
"/",
|
|
"/index.html",
|
|
"/offline.html",
|
|
"/help/index.html",
|
|
"/js/app.js",
|
|
]);
|
|
}),
|
|
);
|
|
});
|
|
|
|
self.addEventListener("activate", function (event) {
|
|
console.log("[SW activate]", event);
|
|
event.waitUntil(
|
|
caches.keys().then((keys) => {
|
|
console.log("removing the old cache");
|
|
return Promise.all(
|
|
keys.map((key) => {
|
|
if (key !== CACHE_STATIC_NAME) {
|
|
return caches.delete(key);
|
|
}
|
|
}),
|
|
);
|
|
}),
|
|
);
|
|
return self.clients.claim();
|
|
});
|
|
|
|
// self.addEventListener("fetch", function (event) {
|
|
// event.respondWith(
|
|
// caches.match(event.request).then((res) => {
|
|
// console.log("res", res);
|
|
// if (res) {
|
|
// return res;
|
|
// } else {
|
|
// return fetch(event.request.url)
|
|
// .then((res) => {
|
|
// return caches.open(CACHE_DYNAMIC_NAME).then((cache) => {
|
|
// cache.put(event.request.url, res.clone());
|
|
// return res;
|
|
// });
|
|
// })
|
|
// .catch(() => {
|
|
// return caches.open(CACHE_STATIC_NAME).then((cache) => {
|
|
// return cache.match("/offline.html");
|
|
// });
|
|
// });
|
|
// }
|
|
// }),
|
|
// );
|
|
// });
|
|
|
|
// Strategy: cache with network fallback
|
|
|
|
// self.addEventListener("fetch", (event) => {
|
|
// event.respondWith(
|
|
// caches.open(CACHE_STATIC_NAME).then((cache) => {
|
|
// return cache.match(event.request).then((res) => {
|
|
// return res || fetch(event.request);
|
|
// });
|
|
// }),
|
|
// );
|
|
// });
|
|
|
|
// Strategy: cache only
|
|
|
|
// self.addEventListener("fetch", (event) => {
|
|
// event.respondWith(caches.match(event.request));
|
|
// });
|
|
|
|
// Strategy: network only
|
|
// does not make sense to use an interceptor in this case at all
|
|
// so there is no need of any request listener
|
|
|
|
// browser ignores this because we are not intercepting
|
|
self.addEventListener("fetch", (event) => {
|
|
return fetch(event.request);
|
|
});
|
|
|
|
// same result at end but intercepting with SW
|
|
self.addEventListener("fetch", (event) => {
|
|
event.respondWith(fetch(event.request));
|
|
});
|