I've been reading through the html5rocks Introduction to service worker article and have created a basic service worker that caches the page, JS and CSS which works as expected:
var CACHE_NAME = 'my-site-cache-v1'; var urlsToCache = [ '/' ]; // Set the callback for the install step self.addEventListener('install', function (event) { // Perform install steps event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('fetch', function (event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; } // IMPORTANT: Clone the request. A request is a stream and // can only be consumed once. Since we are consuming this // once by cache and once by the browser for fetch, we need // to clone the response var fetchRequest = event.request.clone(); return fetch(fetchRequest).then( function(response) { // Check if we received a valid response if(!response || response.status !== 200 || response.type !== 'basic') { return response; } // IMPORTANT: Clone the response. A response is a stream // and because we want the browser to consume the response // as well as the cache consuming the response, we need // to clone it so we have 2 stream. var responseToCache = response.clone(); caches.open(CACHE_NAME) .then(function(cache) { cache.put(event.request, responseToCache); }); return response; } ); }) ); });
When I make a change to the CSS, this change is not being picked up as the service worker is correctly returning the CSS from the cache.
Where I'm stuck is if I were to change the HTML, JS or CSS, how would I make sure that the service-worker loads the newer version from the server if it can rather than from the cache? I've tried using version stamps on the CSS import but that didn't seem to work.
Open the app in your browser (http://localhost:8443/). Turn off “Update on reload” if it is on (see “Service Worker Lifecycle”). Delete all existing service workers registered to this page. In Chrome, this can be achieved by using the “Clear storage” tool in the Application panel of the developer tools.
update() The update() method of the ServiceWorkerRegistration interface attempts to update the service worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker.
Service workers are a fundamental part of a PWA. They enable fast loading (regardless of the network), offline access, push notifications, and other capabilities. Users expect apps to start on slow or flaky network connections, or even when offline.
You can launch a PWA from your home screen, do what you have to do with it, then launch another app, and go back to the PWA the next day. If you haven't closed the app or turned off your phone in the meantime, it will not reload the page — instead it will simply allow you to continue your session where you left off.
One option is just to use a the service worker's cache as a fallback, and always attempt to go network-first via a fetch()
. You lose some performance gains that a cache-first strategy offers, though.
An alternative approach would be to use sw-precache
to generate your service worker script as part of your site's build process.
The service worker that it generates will use a hash of the file's contents to detect changes, and automatically update the cache when a new version is deployed. It will also use a cache-busting URL query parameter to ensure that you don't accidentally populate your service worker cache with an out-of-date version from the HTTP cache.
In practice, you'll end up with a service worker that uses a performance-friendly cache-first strategy, but the cache will get updated "in the background" after the page loads so that the next time it's visited, everything is fresh. If you want, it's possible to display a message to the user letting them know that there's updated content available and prompting them to reload.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With