Everything You Need to Know About PWAs — Workbox
Workbox is a collection of flexible abstractions that let us do hard things more simply
Adding pre-caching, caching strategies, routing, and background sync for your progressive web app is complicated.
Workbox is a collection of flexible abstractions that let us do hard things more simply.
In a nutshell, Workbox lets us do the following, easily:
- Serve cache-first images, HTML, and CSS styles to increase web apps’ performance.
- Automatic cache cleanups, and updates.
- Runtime caching.
- Request routing.
- Background sync.
Getting Started With Workbox
Workbox gives us a handy command line tool out of the box.
yarn add workbox-cli
Once we have the CLI, run the wizard. Enter the relative paths for your app.
npx workbox wizard
You should see a new file
workbox-config.js appear at the root of your project.
The config file defines our root directory, which files to cache and where our
Generate the Service Worker File
npx workbox generateSW workbox-config.js
You should see the
sw.js file appear, which might look like something like this:
It’s a long file, but basically, it installs
workbox and tells the browser which files to cache.
You can remove the
service-worker.js file and register our new service worker —
If we relaunch and open our browser, we should have offline support, caching and fetching cached assets enabled now.
Click on the offline box and try refreshing. If you check the
Cache Storage tab, you should see everything stored in the cache. Magic!
As of now, we can’t modify the generated file, because any change we make will be overwritten as soon as we re-generate the service worker file.
If you would like to modify the
sw.js, here’s how you can do it:
Create a new file called
src-sw.js with the following contents. The content of the
src-sw.js file will be injected inside the
Tell the original
sw.js file where the
src-sw.js is located.
Finally, run the command:
npx workbox injectManifest
Now we should see the
console.log show up in the
Workbox can do much, much more. Please read the documentation to try out different features.
Where to go from here?
I highly recommend building stuff. Building stuff is by far the best way to get good at things, here’s a list of fun apps to build.
If you want to learn about progressive web apps in-depth, I’d suggest reading through the “Building Progressive Web Apps: Bringing the Power of Native to the Browser” book.
Here’s the source code for this chapter.
Contribute to indreklasn/pwa-example development by creating an account on GitHub.
Thanks for reading!