Reputation: 18144
I've sw.js code like:
self.addEventListener('install', e => {
e.waitUntil(
caches.open('cache').then(cache => {
return cache.addAll([
'/',
'/index.html',
'/styles/main.css',
'/scripts/main.min.js'
])
.then(() => self.skipWaiting());
})
)
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
I've updated the index.html file recently, but the file isn't reflected the site. It's still showing the old content of index.html.
Now, How can I make sure app will be serving the latest code if file's changed on the server?
I've been seeing some related answers (like update and refresh), but please tell me what's going on each part of the answer.
Upvotes: 0
Views: 1095
Reputation: 56044
You have two options:
fetch
handler to a strategy like stale-while-revalidate.install
and activate
handlers, giving them a chance to update your users' caches with the latest copies of your assets. These tools work by generating hashes of each local file and inlining those hashes into the generated service worker script.Option 2. is more efficient, because your users will only have to make requests for your assets when something actually changes, as opposed to when using a stale-while-revalidate strategy, which requires firing off a "revalidate" request in the background each time your fetch
handler is invoked. Option 2. does require a bit more work, though, because you need to incorporate a step into your build process to generate your service worker for you.
If you go the option 2. route, there are a few different build tools that I know about:
sw-precache
(disclosure: I'm the author)offline-plugin
Upvotes: 2