With new technological introductions like the Service Worker, Progressive Web Apps are taking the future of web apps to places we never imagined.
The Service Worker, a script that runs in the background of the web browser, separate from the webpage, helps implement offline functionality to web apps, giving the users offline experience like a native app would.
As described on their official website, “Workbox is a set of libraries and Node modules that make it easy to cache assets and take full advantage of features used to build progressive web app’s.”
Workbox automates and abstracts the implementation code you would usually write in your Service Worker script. It takes care of the caching, pre-caching and serving of files according to instructions given through its API.
- Creates an offline first experience for your website
- Improves site performance by serving files cached with various caching strategies
In this article, you will use the workbox library to build offline capable Progressive Web Apps.
You will learn how to:
- Integrate the workbox library into your Service Worker
- Add routes to your service worker using workbox
- Use the predefined caching strategies provided in the workbox library
STEP 1: Create a folder called workbox-pwa. Our final folder structure will look like this:
workbox-pwa ├── README.md ├── index.html ├── sw.js └── src └── Images └── Index.js └── Index.css
STEP 2: Create an index.html file. Here, we will define the basic page structure and include a src/index.js script
STEP 3: In the src/index.js script, we will register our Service Worker script located in the root folder and also populate the index.html page with content. The index.html page will include an image, this will help test the workbox resource caching strategies.
STEP 4: Create a Service Worker file in the root of the site and name it sw.js.
STEP 5: Now that our Service Worker has been installed, we will import the workbox.js library from the CDN to the Service Worker script. This will provide the workbox namespace in your Service Worker, giving you access to all of the workbox modules.
You should get a success response like this in your console
We will use a Stale While Revalidate caching strategy for our css files, that is request for css files will be served from the cache and after that an update is requested from the network to be served on subsequent request.
STEP 6: We will cache all images requested by the site by registering a route that matches when requested resource(s) ends with a valid image extension.
The caching strategy employed here is the Cache First strategy, which checks if the image being requested is available in the cache first, if not, it fetches the image from the network.
We will name the cache image-cache and include a workbox expiration plugin, setting maximum entries, through the maxEntries property of the argument, to 30, that is only 30 images can be stored in the cache as older entries will be removed for newer ones. The maxAgeSeconds property that specifies the maximum length of time an image will remain in the cache is set to one week. This removes any image that’s been in the cache for more than a week.
STEP 7: To enable a full offline experience on the app, we will cache the index page so its still accessible even when the user is offline.
We did something a little different here: Although Workbox comes with helpers that perform the matching and handling function for you, it also allows for writing custom matching and handling functions. So we will use a custom matching function in registering the index page route.
The matchCb function takes the url and event as arguments and returns Trueif the pathname matches the root of the site (The root path of the site, obviously on localhost, is ‘/workbox-pwa/’. You may use ‘/’ while in production if that equals the root of your site), otherwise it returns False.
Note: Your custom matching function must return a truthly value (True or False) and all works must be synchronous as all asynchronous works are prohibited. Your custom handling function on the other hand must return a Promise that resolves to a Response.
Our custom matching function — matchCb — is then passed as first parameter to the workbox’s registerRoute function. The Network First strategy is used here.
Now our Service Worker is ready for use…
Lets add a little design to the page by including an external css file src/index.css. It will also serve as needed resources to be cached by the Service Worker through the workbox library.
The final page should look something like this if you’ve followed the above instructions to the letter.
Navigating to the Application tab in Chrome Dev Tools and clicking on ‘Cache’ at the bottom-left corner shows a list of cache names and the files cached under these cache names.
To check if the app works offline, Navigate to the Application tab in Chrome Dev Tools, click on Service Workers on the left section, then toggle on the offline option. This will take the browser tab offline, restricting access to the network, mimicking a real life device thats completely offline without access to network. That way we can assess the site for offline functionality.
Once this is done, refresh the page.
Yaay 🎉 🎉 ! Your app now works offline.
In this article you have been introduced to its basics and have learnt how to use the workbox library to create offline experience in a Progressive Web App by automating the caching and pre-caching of website resources using various caching strategies through instructions given to the workbox API.
Here’s a link to the Github repository:
Contribute to workbox-pwa development by creating an account on GitHub.github.com
For more comprehensive guides and resources on workbox library, check out these links :
Workbox is a set of service worker libraries that making build progressive web apps easy.developers.google.com
Comments and feedbacks are welcome 😃