Warm the inventory cache on service-worker activate (fix iOS first-install offline)

On a fresh iOS "Add to Home Screen" install the just-installed service worker
is often not yet controlling the page when React fetches /api/inventory, so the
NetworkFirst route never stores it; offline then shows an infinite spinner.
(Safari/standalone storage is also isolated, so priming in Safari doesn't help
the installed app.)

Cache /api/inventory and /api/inventory/catalog explicitly in the activate
handler (cache:'reload' to bypass the HTTP cache), so the first online launch in
standalone mode guarantees an offline copy regardless of fetch/control timing.

Verified locally: fresh install caches the inventory on first load with no manual
reload; cold offline reload renders the inventory read-only instead of spinning.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-06-22 17:49:47 -06:00
parent f87921e2a7
commit 201df63e30
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680

View file

@ -54,6 +54,21 @@ registerRoute(
})
);
// Proactively cache the inventory (and food catalog) the moment the worker activates, while the device is still
// online. Relying on the page's first fetch is unreliable - especially on a fresh iOS "Add to Home Screen"
// install, where the just-installed worker is often not yet controlling the page when React fetches the
// inventory, so the NetworkFirst route never stores it and the offline page spins forever. Caching at activate
// (with cache:'reload' to bypass the HTTP cache) guarantees an offline copy after the first online launch.
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
const cache = await caches.open('wrolpi-inventory');
await Promise.allSettled([
cache.add(new Request('/api/inventory', {cache: 'reload'})),
cache.add(new Request('/api/inventory/catalog', {cache: 'reload'})),
]);
})());
});
// Allow the page to tell a waiting SW to activate immediately (used by the update flow).
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {