aboutsummaryrefslogtreecommitdiff
path: root/internal/ui/static/js/service_worker.js
diff options
context:
space:
mode:
authorGravatar Frédéric Guillot <f@miniflux.net> 2023-08-10 19:46:45 -0700
committerGravatar Frédéric Guillot <f@miniflux.net> 2023-08-10 20:29:34 -0700
commit168a870c025bfef6efdeb46e166e79a16093c157 (patch)
tree4d8ab69c7e3ef03a7ade06e7b5e5053429a64c3b /internal/ui/static/js/service_worker.js
parentc2349032552891745cbbc3d2a9e772845a0239f4 (diff)
downloadv2-168a870c025bfef6efdeb46e166e79a16093c157.tar.gz
v2-168a870c025bfef6efdeb46e166e79a16093c157.tar.zst
v2-168a870c025bfef6efdeb46e166e79a16093c157.zip
Move internal packages to an internal folder
For reference: https://go.dev/doc/go1.4#internalpackages
Diffstat (limited to 'internal/ui/static/js/service_worker.js')
-rw-r--r--internal/ui/static/js/service_worker.js44
1 files changed, 44 insertions, 0 deletions
diff --git a/internal/ui/static/js/service_worker.js b/internal/ui/static/js/service_worker.js
new file mode 100644
index 00000000..37cce257
--- /dev/null
+++ b/internal/ui/static/js/service_worker.js
@@ -0,0 +1,44 @@
+
+// Incrementing OFFLINE_VERSION will kick off the install event and force
+// previously cached resources to be updated from the network.
+const OFFLINE_VERSION = 1;
+const CACHE_NAME = "offline";
+
+self.addEventListener("install", (event) => {
+ event.waitUntil(
+ (async () => {
+ const cache = await caches.open(CACHE_NAME);
+
+ // Setting {cache: 'reload'} in the new request will ensure that the
+ // response isn't fulfilled from the HTTP cache; i.e., it will be from
+ // the network.
+ await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
+ })()
+ );
+
+ // Force the waiting service worker to become the active service worker.
+ self.skipWaiting();
+});
+
+self.addEventListener("fetch", (event) => {
+ // We proxify requests through fetch() only if we are offline because it's slower.
+ if (navigator.onLine === false && event.request.mode === "navigate") {
+ event.respondWith(
+ (async () => {
+ try {
+ // Always try the network first.
+ const networkResponse = await fetch(event.request);
+ return networkResponse;
+ } catch (error) {
+ // catch is only triggered if an exception is thrown, which is likely
+ // due to a network error.
+ // If fetch() returns a valid HTTP response with a response code in
+ // the 4xx or 5xx range, the catch() will NOT be called.
+ const cache = await caches.open(CACHE_NAME);
+ const cachedResponse = await cache.match(OFFLINE_URL);
+ return cachedResponse;
+ }
+ })()
+ );
+ }
+});