IMP: improve service worker update flow to avoid stale cache and disruptive reloads

This commit is contained in:
Julien Maille 2026-01-02 13:45:33 +01:00
parent 0b9eea86ab
commit 63c342b693
3 changed files with 26 additions and 16 deletions

View file

@ -735,16 +735,5 @@
</footer>
</div>
<script type="module" src="js/app.js"></script>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(reg => {
reg.update();
});
navigator.serviceWorker.addEventListener('controllerchange', () => {
location.reload();
});
}
</script>
</body>
</html>

View file

@ -649,17 +649,25 @@ if (e.target.closest('#delete-playlist-btn')) {
.then(reg => {
console.log('Service worker registered');
if (reg.waiting) {
showUpdateNotification(reg.waiting);
}
reg.addEventListener('updatefound', () => {
const newWorker = reg.installing;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
showUpdateNotification();
showUpdateNotification(newWorker);
}
});
});
})
.catch(err => console.log('Service worker not registered', err));
});
navigator.serviceWorker.addEventListener('controllerchange', () => {
window.location.reload();
});
}
let deferredPrompt;
@ -699,7 +707,7 @@ if (e.target.closest('#delete-playlist-btn')) {
});
});
function showUpdateNotification() {
function showUpdateNotification(worker) {
const notification = document.createElement('div');
notification.className = 'update-notification';
notification.innerHTML = `
@ -707,9 +715,17 @@ function showUpdateNotification() {
<strong>Update Available</strong>
<p>A new version of Monochrome is available.</p>
</div>
<button class="btn-secondary" onclick="window.location.reload()">Update Now</button>
<button class="btn-secondary" id="update-now-btn">Update Now</button>
`;
document.body.appendChild(notification);
document.getElementById('update-now-btn').addEventListener('click', () => {
if (worker) {
worker.postMessage({ action: 'skipWaiting' });
} else {
window.location.reload();
}
});
}
function showInstallPrompt(deferredPrompt) {

9
sw.js
View file

@ -1,5 +1,5 @@
// sw.js
const SW_VERSION = 'monochrome-v6'; // Note To Self: Change Every Deploy
const SW_VERSION = 'monochrome-v7'; // Note To Self: Change Every Deploy
const CACHE_NAME = `monochrome-${SW_VERSION}`;
const ASSETS = [
@ -31,12 +31,17 @@ const ASSETS = [
];
self.addEventListener('install', event => {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS))
);
});
self.addEventListener('message', (event) => {
if (event.data && event.data.action === 'skipWaiting') {
self.skipWaiting();
}
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>