Native apps are known for their extensive capabilities, given that they are one with the device on which they are installed. Web apps do not boast the same capabilities as native apps. However, because they are browser-dependent, they are known to have a higher reach. Progressive Web Apps combines the best of both worlds. These apps are developed with standard programming and scripting languages like CSS, HTML, JavaScript, much like any website. A PWA can be accessed via any standards-compliant browser. It has offline functionality and push notifications. These apps can also access any device’s hardware, much like native apps. Perhaps the best part is that they can be used by any kind of business, from digital marketing authorities like Neil Patel to custom writing review services like Best Writers Online and Online Writers Rating. Anyone brand can utilize web apps to their advantage.
How can you develop a PWA?
The most popular way would be through Google’s Workbox. Any developer who has used sw–toolbox and sw–precache will appreciate the step up that is Workbox. It can be used for service worker generation, to precache, route, and runtime-cache, thanks to its robust tools and libraries. Workbox can also help with syncing your service worker with Google Analytics and background sync.
To write your own PWA with Workbox essentially involves you creating a service worker. For this, you’ll need to work through the library that is workbox-sw.js and also the Node.js (the workbox–cli module).
Prerequisites for PWA development using Workbox:
- Basic front-end development knowledge of JavaScript, HTML, and CSS
- The Promises feature on ES2015 (ES6)
- Knowledge of command line operation
- Fair experience with service workers
- Reasonable experience working with Node.js
- Internet connection
- Standards-compliant browser
- Access to terminal/shell via a desktop/laptop
- Any text editor
- js and Node package manager (npm)
The following steps will help you run a basic service worker for a simple blog-style PWA via Google’s Workbox. This way, you can get a feel of what a PWA can do for you.
#1 Install Node.js
Follow this link to get your hands on Node.js’s latest long-term support version. Visit Github to download starter code in zip file format. Or you could just clone it from Github with this command:
git clone https://github.com/googlecodelabs/workbox-lab.git
This step is not needed if you already have the Node.js LTS.
#2 Set up the project dependencies and launch server
In the command line, get to the project directory, using:
cd workbox-lab/project/
Then execute the commands below:
npm install
npm install –global workbox-cli@^3.0.0
These will ready the project dependencies.
Next, run these app building and serving commands:
npm run build
npm run start
You can visit http://localhost:8081/ to launch the app and check it out. Bear in mind that at this point, we’ve still got an empty service worker.
#3 Use workbox-sw to make a basic service worker
Now that we have a functional starting app, add the below code snippet in the file of the service worker, src/sw.js (this file can is in the workbox-lab/project folder):
src/sw.js
importScripts(‘https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js’);
if (workbox) {
console.log(`Yay! Workbox is loaded 🎉`);
workbox.precaching.precacheAndRoute([]);
} else {
console.log(`Boo! Workbox didn’t load 😬`);
}
Save after inputting this in the src/sw.js file.
#4 Configure the Workbox
The next step is to create the configuration file for the workbox-cli. This is the prerequisite step to take to inject the service worker with a precache manifest.
Input this command from the project directory.
workbox wizard –injectManifest
The command line will deliver a few prompts after this.
- When the first prompt requires the root path from you. Respond to this prompt by typing “build/.” This response may be suggested by the prompt itself, in which case, you can just choose the “build/” from the list.
- The prompt that follows will ask for the cache file types. Select only the cache CSS files.
- Here you will provide your service worker’s source path—src/sw.js. Simply input this file name and click return.
- The next prompt is the path for writing the production service worker. Input “build/sw.js” and click return again.
- This, the last prompt, will require you to give your configuration file a name. Simply click return and use “workbox-config.js,” which should be given to you as this prompt’s default answer.
For now, ignore any instruction log that comes up to help you build your service worker. This step will be taken care of later in the build process.
#5 Inject the service worker with precache manifest using the workbox-cli
To run the injectManifest command in Workbox, you must update the build script in the package.json.
{
“name”: “workbox-lab”,
“version”: “1.0.0”,
“description”: “a lab for learning workbox”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″,
“copy”: “copyfiles -u 1 src/**/**/* src/**/* src/* build”,
“build”: “npm run copy && workbox injectManifest workbox-config.js”,
“start”: “node server.js”
},
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“express”: “^4.16.3”
},
“devDependencies”: {
“copyfiles”: “^1.2.0”,
“workbox-cli”: “^3.5.0”
Run the npm run build command after saving the file. At this point, your build/sw.js file should be updated with the precacheAndRoute call. Check for the style/main.css in the file manifest of build/sw.js via the text editor.
Again, open http://localhost:8081/ and go to developer tools in your browser (use the shortcut Ctrl+Shift+I in Google Chrome; and Cmd+Opt+I for Mac). To test your new service worker, Unregister, and delete all your localhost’s service worker caches. Alternatively, you can simply do Application > Clear Storage > Clear site data in Chrome DevTools.
Do a page refresh to ensure the correct installation of your new service worker. Also, doublecheck your cache to ensure that your main.css is stored.
#6 Reinject an updated manifest
Next, take out the contents of workbox-config.js file and replace it with the following snippet:
module.exports = {
“globDirectory”: “build/”,
“globPatterns”: [
“**/*.css”,
“index.html”,
“js/animation.js”,
“images/home/*.jpg”,
“images/icon/*.svg”
],
“swSrc”: “src/sw.js”,
“swDest”: “build/sw.js”,
“globIgnores”: [
“../workbox-config.js”
]
};
Save the file. Run the npm run build from the project directory for updating build/sw.js precache manifest. The manifest should now include index.html, business.jpg, icon.svg, main.css, and also animation.js.
To update your new service worker, first, do an app refresh. And then in your Chrome DevTools do Application > Service Workers > skipWaiting. The globPatterns file should be in the cache now.
Turn off the server in the command line window where you ran the npm run start command. Do this by pressing Ctrl+C. Your home page should still load if you refresh it now.
#7 Service worker routes addition
The code below is for adding routes to your service worker.
workbox.routing.registerRoute(
/(.*)articles(.*)\.(?:png|gif|jpg)/,
workbox.strategies.cacheFirst({
cacheName: ‘images-cache’,
plugins: [
new workbox.expiration.Plugin({
maxEntries: 50,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
})
]
})
);
The code above should be placed under the precacheAndRoute call in the src/sw.js file. Make sure not to touch the build/sw.js to avoid overwriting the file when workbox injectManifest is run again.
Save the file and do a server restart. Then use the commands below to rebuild the app and service worker again.
npm run build
npm run start
Again, refresh the updated service worker to activate it. And ensure that the images–cache is in the caches.
#8 Use and customize a networkFirst cache strategy
Using the networkFirst strategy is the best option to keep content updated on your PWA. This way, old content will only be fetched by the service worker if this cache strategy does not work.
In the src/sw.js, add the code below:
const articleHandler = workbox.strategies.networkFirst({
cacheName: ‘articles-cache’,
plugins: [
new workbox.expiration.Plugin({
maxEntries: 50,
})
]
});
workbox.routing.registerRoute(/(.*)article(.*)\.html/, args => {
return articleHandler.handle(args);
});
As always, save the file, run npm run build, clear cache in Chrome DevTools, and use the browser to update the service worker.
Hit refresh on the home page and click one of the Trending Articles. Remember to check and ensure the creation of the articles–cache was successful. Also, check if the Trending Article is present in the cache.
#9 Test the apps offline and asynchronous functionality
This one is optional. To evaluate the dynamic caching, click more articles within the app, and visit them. Then use Ctrl+C to take the app offline in the command line window. Open the app while offline and revisit the articles. You should still see the cached article instead of the browser’s offline page. Don’t forget to restart the server using the npm run start command. Another check. Choose one of the cached articles and change its content. Run the npm run build for updating the build files. Then reload the article. Even with the old article still cached, you should be served with the altered article, and the cache should be updated.
Conclusion
At this point, you understand how to work with Workbox, and how to build a service worker that is functional and production-ready. What kind of web app do you plan to create with this? Your imagination is your limit!
Credit
Gregory is passionate about researching on new technologies in both mobile, web and WordPress. Gregory in love with stories and facts, so Gregory always tries to get the best of both worlds.