66 lines
1.9 KiB
JavaScript
66 lines
1.9 KiB
JavaScript
|
|
// Favoritter — Service Worker for PWA offline support.
|
||
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||
|
|
|
||
|
|
var BASE = "{{BASE_PATH}}";
|
||
|
|
var CACHE_NAME = "favoritter-v1";
|
||
|
|
var STATIC_URLS = [
|
||
|
|
BASE + "/static/vendor/pico.min.css",
|
||
|
|
BASE + "/static/vendor/htmx.min.js",
|
||
|
|
BASE + "/static/css/style.css",
|
||
|
|
BASE + "/static/js/app.js",
|
||
|
|
BASE + "/static/icons/icon-192.png"
|
||
|
|
];
|
||
|
|
|
||
|
|
self.addEventListener("install", function (event) {
|
||
|
|
event.waitUntil(
|
||
|
|
caches.open(CACHE_NAME).then(function (cache) {
|
||
|
|
return cache.addAll(STATIC_URLS);
|
||
|
|
})
|
||
|
|
);
|
||
|
|
self.skipWaiting();
|
||
|
|
});
|
||
|
|
|
||
|
|
self.addEventListener("activate", function (event) {
|
||
|
|
event.waitUntil(
|
||
|
|
caches.keys().then(function (names) {
|
||
|
|
return Promise.all(
|
||
|
|
names.filter(function (n) { return n !== CACHE_NAME; })
|
||
|
|
.map(function (n) { return caches.delete(n); })
|
||
|
|
);
|
||
|
|
})
|
||
|
|
);
|
||
|
|
self.clients.claim();
|
||
|
|
});
|
||
|
|
|
||
|
|
self.addEventListener("fetch", function (event) {
|
||
|
|
var url = new URL(event.request.url);
|
||
|
|
|
||
|
|
// Cache-first for static assets.
|
||
|
|
if (url.pathname.startsWith(BASE + "/static/")) {
|
||
|
|
event.respondWith(
|
||
|
|
caches.match(event.request).then(function (cached) {
|
||
|
|
return cached || fetch(event.request).then(function (response) {
|
||
|
|
var clone = response.clone();
|
||
|
|
caches.open(CACHE_NAME).then(function (cache) {
|
||
|
|
cache.put(event.request, clone);
|
||
|
|
});
|
||
|
|
return response;
|
||
|
|
});
|
||
|
|
})
|
||
|
|
);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Network-first for navigation (HTML pages).
|
||
|
|
if (event.request.mode === "navigate") {
|
||
|
|
event.respondWith(
|
||
|
|
fetch(event.request).catch(function () {
|
||
|
|
return caches.match(event.request);
|
||
|
|
})
|
||
|
|
);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Default: network only.
|
||
|
|
event.respondWith(fetch(event.request));
|
||
|
|
});
|