mirror of
https://github.com/zoldar/jenot.git
synced 2026-01-05 07:02:55 +00:00
Add basic caching service worker
This commit is contained in:
parent
6e4b32debf
commit
8d7e264ffb
3 changed files with 61 additions and 0 deletions
37
js/caching-worker.js
Normal file
37
js/caching-worker.js
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
const putInCache = async (request, response) => {
|
||||||
|
const cache = await caches.open("v1");
|
||||||
|
await cache.put(request, response);
|
||||||
|
};
|
||||||
|
|
||||||
|
const cacheFirst = async ({ request, fallbackUrl }) => {
|
||||||
|
const responseFromCache = await caches.match(request);
|
||||||
|
if (responseFromCache) {
|
||||||
|
return responseFromCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const responseFromNetwork = await fetch(request);
|
||||||
|
// Cloning is needed because a response can only be consumed once.
|
||||||
|
putInCache(request, responseFromNetwork.clone());
|
||||||
|
return responseFromNetwork;
|
||||||
|
} catch (error) {
|
||||||
|
const fallbackResponse = await caches.match(fallbackUrl);
|
||||||
|
if (fallbackResponse) {
|
||||||
|
return fallbackResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response("Network error happened", {
|
||||||
|
status: 408,
|
||||||
|
headers: { "Content-Type": "text/plain" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
self.addEventListener("fetch", (event) => {
|
||||||
|
event.respondWith(
|
||||||
|
cacheFirst({
|
||||||
|
request: event.request,
|
||||||
|
fallbackUrl: "/index.html",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import "./service-worker.js";
|
||||||
import { renderText } from "./dom.js";
|
import { renderText } from "./dom.js";
|
||||||
import { NoteStore } from "./store.js";
|
import { NoteStore } from "./store.js";
|
||||||
import "./components.js";
|
import "./components.js";
|
||||||
|
|
|
||||||
23
js/service-worker.js
Normal file
23
js/service-worker.js
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
const registerServiceWorker = async () => {
|
||||||
|
if ("serviceWorker" in navigator) {
|
||||||
|
try {
|
||||||
|
const registration = await navigator.serviceWorker.register(
|
||||||
|
"/js/caching-worker.js",
|
||||||
|
{
|
||||||
|
scope: "/",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (registration.installing) {
|
||||||
|
console.log("Service worker installing");
|
||||||
|
} else if (registration.waiting) {
|
||||||
|
console.log("Service worker installed");
|
||||||
|
} else if (registration.active) {
|
||||||
|
console.log("Service worker active");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Registration failed with ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
registerServiceWorker();
|
||||||
Loading…
Add table
Reference in a new issue