trip-day-tracker/sw.js

53 lines
1.9 KiB
JavaScript

/* Business Trip Day Tracker — offline shell.
Cache-first on purpose: this app is a static document whose whole point is
working in airplane mode, so a stale-by-a-day shell beats a failed load.
Bump CACHE when index.html changes; activate() drops every older cache. */
var CACHE = "trip-tracker-v3";
var ASSETS = ["./", "./index.html", "./manifest.webmanifest", "./icon-512.png"];
self.addEventListener("install", function(e){
e.waitUntil(
caches.open(CACHE).then(function(c){
/* addAll is all-or-nothing; one 404 would leave us with no offline copy
at all, so fetch them individually and keep whatever succeeds. */
return Promise.all(ASSETS.map(function(u){
return fetch(u, {cache:"reload"})
.then(function(r){ if(r && r.ok) return c.put(u, r); })
.catch(function(){});
}));
}).then(function(){ return self.skipWaiting(); })
);
});
self.addEventListener("activate", function(e){
e.waitUntil(
caches.keys().then(function(keys){
return Promise.all(keys.map(function(k){
return k === CACHE ? null : caches.delete(k);
}));
}).then(function(){ return self.clients.claim(); })
);
});
self.addEventListener("fetch", function(e){
var req = e.request;
if(req.method !== "GET") return;
if(new URL(req.url).origin !== self.location.origin) return;
e.respondWith(
caches.match(req, {ignoreSearch:true}).then(function(hit){
if(hit) return hit;
return fetch(req).then(function(res){
if(res && res.ok){
var copy = res.clone();
caches.open(CACHE).then(function(c){ c.put(req, copy); });
}
return res;
}).catch(function(){
/* Offline and not cached — a navigation still gets the app shell. */
if(req.mode === "navigate") return caches.match("./index.html");
throw new Error("offline");
});
})
);
});