The Curse of the astray Service Worker
When I published my new site last week, I continued to still see my old site. Initially I thought it was just DNS, but after a short while it dawned on me, that my old site used a Service Worker which cached everything and made it offline available. When you visited my old site, it automatically installed the Service Worker, and continued to serve it from cache. And now, if you visited my new site, it still served my old site. Great.
My old site used Gatsby, and while browsing through Gatsby's plugins, I saw a plugin to make it offline available and I just installed it, because why not. It sounded cool. I had no real experience with those Service Workers. After using it for a while, I didn't really like the User Experience of it. Every time I published a new post, it still showed old posts with a banner "New content available, please reload". But I also kept it because it didn't bother me too much.
I could just go into the Dev Tools and unregister the Service Worker myself, but that would only solve it for me. I had no real experience with the Service Worker Cache API, so I had no idea where and how to start to fix this. I first thought that I need to add some JavaScript into the old site's HTML, but of course that didn't make sense, because that's the cached file I cannot update anymore.
How to unregister an old Service Worker
In the end, the solution was kinda easy. The old Service Worker from this Gatsby plugin was automatically created under timomeh.de/sw.js
. I simply created a new sw.js
with some code to unregister itself which I found in this StackOverflow answer.
self.addEventListener('install', function (e) {
self.skipWaiting()
})
self.addEventListener('activate', function (e) {
self.registration
.unregister()
.then(function () {
return self.clients.matchAll()
})
.then(function (clients) {
clients.forEach((client) => client.navigate(client.url))
})
})
For users which still have the Service Worker installed, it will refetch the sw.js
file, run it, it unregisters itself, the page will reload, and the new site was visible. No Service Worker anymore.
Things I'm still unsure about
- Would this problem have fixed itself after some time if I never created this new
sw.js
file? I've read a few discussions saying that Service Workers update themselves every ~24 hours, but would a gonesw.js
also unregister itself after 24 hours? - My gut feeling is: no, because that would make the offline-available aspect not so useful anymore.
- If it would never unregister itself, isn't this kinda bad? For example you're buying a domain from someone else which used a Service Worker, or some malicious code got injected into your page and you cleaned it up, there could still be code running in the background for some users, which you don't even know about.
- Even if it unregisters itself after some time: while it's still registered and you don't know about it, it could do pretty bad things.