Rollup-based dev environment for JavaScript (part 2: Service Workers)

Service Workers

Service Workers are JavaScript files that run “in the background” of your app. They have no direct access to the DOM and run in a different thread than your application code.
They do have access to other APIs, such as IndexedDB, and can act as a proxy between your application and the network.
Workbox uses these features to cache network requests using various strategies, so that our app can be used offline as well as possible, transparently for the user.

Precaching Rollup bundles

In the first part of this guide, we configured Rollup to output 2 formats : esm and system. Since we only want to cache relevant files, we need to generate a ServiceWorker for each format.

npm install --save-dev workbox-cli npm-run-all

HTTP server configuration

Browsers save ServiceWorker files in a different way than traditional HTTP requests, which means we need to disable HTTP cache: Cache-control: no-cache.
Additionally, we decided to put our sw.js files in subdirectories of the server root (public/js/esm/ and public/js/system/), so we need a header to avoid unenjoyable warnings: Service-Worker-Allowed: /.
Here’s a configuration for the server that we set up in the previous article, serve:

Registering our Service Workers

Finally, we need to actually register sw.js from the browser, depending on which output format is used. Here’s an example of how to do it in index.html from the example repository:

--

--

Web dev — https://camillehdl.dev/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store