Fix stale UI cache with network-first app shell and forced SW updates
This commit is contained in:
1 parent
defdfe2200
commit
5003d3ec09
2 files changed
+35
-2
No files matched your search
+12
-1
@@ -297,7 +297,18 @@
|
|||||||
<script src="app.js"></script>
|
<script src="app.js"></script>
|
||||||
<script>
|
<script>
|
||||||
if ('serviceWorker' in navigator) {
|
if ('serviceWorker' in navigator) {
|
||||||
navigator.serviceWorker.register('/sw.js');
|
window.addEventListener('load', () => {
|
||||||
|
navigator.serviceWorker.register('/sw.js').then(reg => {
|
||||||
|
reg.update().catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
let refreshing = false;
|
||||||
|
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
||||||
|
if (refreshing) return;
|
||||||
|
refreshing = true;
|
||||||
|
window.location.reload();
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+23
-1
@@ -1,6 +1,6 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const CACHE = 'weather-v2';
|
const CACHE = 'weather-v3';
|
||||||
|
|
||||||
// App shell — cached on install for offline use
|
// App shell — cached on install for offline use
|
||||||
const PRECACHE = [
|
const PRECACHE = [
|
||||||
@@ -45,6 +45,28 @@ self.addEventListener('fetch', event => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isAppShellRequest =
|
||||||
|
request.mode === 'navigate' ||
|
||||||
|
request.destination === 'document' ||
|
||||||
|
request.destination === 'script' ||
|
||||||
|
request.destination === 'style';
|
||||||
|
|
||||||
|
// Prefer fresh app shell assets so UI updates are visible immediately.
|
||||||
|
if (isAppShellRequest) {
|
||||||
|
event.respondWith(
|
||||||
|
fetch(request)
|
||||||
|
.then(response => {
|
||||||
|
if (response.ok) {
|
||||||
|
const clone = response.clone();
|
||||||
|
caches.open(CACHE).then(cache => cache.put(request, clone));
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
})
|
||||||
|
.catch(() => caches.match(request).then(cached => cached || caches.match('/')))
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
caches.match(request).then(cached => {
|
caches.match(request).then(cached => {
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|||||||
Reference in new issue
Block a user