A 5 minute intro to Workbox 3.0

Jad Joubran
Google Developer Experts
6 min readJan 3, 2018

Workbox is a collection of JavaScript libraries that help you with service worker related functionalities when you’re building Progressive Web Apps.

In this article, I’m only going to focus on using workbox to generate the service worker file for your application.

W̵o̵r̵k̵b̵o̵x̵ ̵J̵S̵ ̵i̵s̵ ̵c̵u̵r̵r̵e̵n̵t̵l̵y̵ ̵i̵n̵ ̵A̵l̵p̵h̵a̵.̵ ̵I̵ ̵w̵i̵l̵l̵ ̵k̵e̵e̵p̵ ̵t̵h̵i̵s̵ ̵a̵r̵t̵i̵c̵l̵e̵ ̵u̵p̵ ̵t̵o̵ ̵d̵a̵t̵e̵ ̵a̵s̵ ̵W̵o̵r̵k̵b̵o̵x̵ ̵3̵ ̵r̵e̵a̵c̵h̵e̵s̵ ̵a̵ ̵s̵t̵a̵b̵l̵e̵ ̵r̵e̵l̵e̵a̵s̵e̵.̵

Workbox 3.0.0 was released on March 14 🎉

🤔 Why workbox?

I’ve previously used sw-precache & sw-toolbox when working with Progressive Web Apps. However, after hearing about it in the last Chrome Dev Summit and now that I’ve seen the Workbox 3, I’m so excited to switch as Workbox 3 focuses on delivering better modularity, powerful debugging support, all while keeping the library size small 😍.

💻 Follow along

The approach that I take when teaching new technologies is to go a bit low level while isolating concepts.

This is the same approach that Nicole Saidy and I take when presenting PWAworkshop.com at conferences & private companies. So that’s why the repository that I prepared has a build folder which simulates the result of a build tool.

We’re omitting the build step here to make sure you understand how workbox works.

So to follow along this tutorial, start by cloning this repository and installing its dependencies:

The only dependency that we’re installing is http-server which will let you serve your application in the browser.

This is the folder structure that we have at the moment:

.
├── build
│ ├── css
│ │ └── app.css
│ ├── index.html
│ └── js
│ └── app.js
└── package.json

🔗 Install workbox

Let’s start by installing the latest pre-release version of Workbox-cli

npm install workbox-cli --save-dev
Install workbox

I prefer installing libraries locally rather than globally in order to avoid unexpected problems when working on multiple projects.

So because we installed workbox locally, you can now invoke it by using npx

npx workbox (rather than justworkbox).

🎩 Workbox wizard

The first Workbox command that we’re going to go through is wizard.

workbox wizard scans your directory and asks you a series of questions in order to generate a workbox-config.js that will be used later on whenever you invoke workbox.

npx workbox wizard

and now workbox will ask you a series of questions.

Answer with yes to all the questions, since all the defaults make sense and you can simply edit the file later on if you need to.

Workbox wizard

You will now have a workbox-config.js at the root, containing the below configuration:

🏋️‍ Workbox generateSW

This workbox command will read your workbox-config.js and generate a service-worker file that pre-caches files based on the globPatterns that we got from workbox wizard: **/*.{css,html,js}.

npx workbox generateSW workbox-config.js
Workbox generateSW

Register the service worker

Now that the service worker file has been generated, we have to register it.

So let’s go into the index.html and add the following piece of code before the closing tag of the body:

Serve it

Now serve your app by running npm run serve and head to http://localhost:8080/ in your browser.

Voila! In the Network tab of Chrome dev tools, you can see the requests made by the service-worker which are prefixed by the ⚙️ icon. Workbox will only load the .dev.js helpers when you’re developing locally.

Workbox will also request the index.html, app.css & app.js with a specific workbox-cache-buest parameter to make sure you get the latest version of your assets.

Workbox pre-caching assets

You can also inspect these pre-cached assets by going into Application > Cache Storage (you may need to right-click & refresh) > workbox-precache.

In this revamped dev tools page, you can see the cached assets alongside their content which is shown in the Preview tab.

Preview pre-cached assets

Go offline!

Go back to the Network tab and make yourself Offline.

Reload the page and you will see that you still get a response for the index.html, app.js & app.css. That’s because they have been pre-cached and are being served even when offline.

Works offline!

💉 Workbox injectManifest

As you can see, the entire service worker file is now generated by Workbox. But what if you want to change one thing? What if you want to add one line? Add offline analytics?

You cannot change the generated file because any change you make will be overwritten as soon as you re-generate the service worker file.

This is why you have to use injectManifest whenever you want to stay in control of your service-worker file and let Workbox generate part of it.

So we need to have a source service worker file, that will be used to generate the final service worker.

Let’s create src-sw.js file at the root of your project and write the following code in side of it:

So we’re importing workbox from CDN, adding some custom code (for now it’s simply a console log) and then adding a placeholder: workbox.precaching.precacheAndRoute([]); .

Workbox will generate the precaching array and inject it into this line of code: workbox.precaching.precacheAndRoute([]); while keeping the rest of the code intact.

Now in workbox-config.js, add the following line:

"swSrc": "src-sw.js"

You should end up having this configuration in your workbox-config.js:

Now simply run: npx workbox injectManifest

Workbox injectManifest

And here’s the generated service worker that you’ll get:

🛣 Workbox routing

We’ve done pre-caching so far, where we instruct workbox to add some resources to the cache because we will be using them later on.

But what about dynamic resources? What if you call a specific API and you want to cache its response?

Here comes the job of Workbox routing which allows you to define a regular expression that matches a specific request with a strategy.

You could define your own strategy but most of the times you’d use one of these 3 that are already existing:

You can find more explanation on how they work in the workbox strategies docs.

If you take a look at the build/js/app.js, we have a fetch request to https://jsonplaceholder.typicode.com/users, so in order to cache the results of this link, I’m going to use the cacheFirst strategy and register the route using a regular expression that matches the url, which is:

new RegExp('https://jsonplaceholder.typicode.com/users').

Now simply register the route as below in your src-sw.js file by placing it under the console.log('this is my custom service worker');.

And let’s regenerate the service worker file by running npx workbox injectManifest.

I encourage you to take a look at the newly generated service worker in build/sw.js just to make sure that you strengthen these concepts in your head.

Serve it

If you stopped serving your app, you can do it again by running npm run serve.

Then reload the page once in order to get the new service worker, then reload it again in order to cache the response of /users in the cache (using the new service worker code) and then go offline.

/users is served from ServiceWorker

Checkout how the fetch request to /users is being served from the cache.

🚀 Done!

With that, you’re ready to dive deeper into workbox and build awesome PWAs.

A big thank you for the Workbox core team for building an awesome library.

Jeffrey Posnick, Matt Gaunt, Addy Osmani, Philip Walton, PRATEEK BHATNAGAR & Kayce Basques

Are you looking for an intro to Progressive Web Apps before you get started with Workbox? Then checkout the video series below!

--

--