[PWA Series] Service workers Cookbook — Part 1
This is the 2nd article of the PWA series. In the first article we saw how you can add — “Add to home screen” icon in your PWA app.
Thank you Abhishar Jangir — he added a point that you need secure to get the notification of Add to Homescreen box.
In this article we will learn the backbone of the PWA — Service workers. They help making our PWA — Fast, offline support, Push notifications , presenting the updated content always and much more.
For user to to use an app it always come to the two main factors:
- Data cost
- Size of the app
Users are very intelligent and picky when it comes to what they want to install on their mobile and what to not. Developers & product managers of native apps are struggling every day to get the traffic to their native apps. They are squeezing the app size to get the space on the user’s mobile yet the compition is very high.
PWA is the blessing not just for the user as well as for the developer and product managers too. Wondering how? The magic is — Service workers
Service workers helps in caching the files and using different strategy to get the files. This will make the app load fast which results in saving the data cost too. Service worker is the most powerful BUT most confusing concept. Mastering this monster is not tough but the learning curve is interesting.
[Side note : Do you IOS announced the support of the Service worker?]
What is Service workers?
A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction. Such as push notifications, background-sync, Offline support etc.
but, there was APICache before service workers!!
Why we need them?
As I said this is the backbone of the PWA. If you are looking how to take advantage of making your app load fast, work offline, cache files (to save some data cost), push notifications, background sync then service worker is the one for you. This is ever growing technology and future has more of it.
Most wonderful thing about the SW is the are pure JS and run on client side.
Understand the monster
- it‘s a JS worker hence it can’t intract and manipulate the DOM. You can send the messages by using POSTMessage API
- Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.
- It’s terminated when not in use, and restarted when it’s next needed, so you cannot rely on global state within a service worker’s
onfetch
andonmessage
handlers. - If there is information that you need to persist and reuse across restarts, service workers do have access to the IndexedDB API.
[ Do you know you can use workbox too with PWA?]
Lifecycle of SW
SW has a lifecycle to follow and it is completley different from Webpage
- Browser Support
- Register
- Activate
- Fetch
Code Time
#1 Browser Support and Register
This is the first step. You need to check if service worker is available or not and how we can progressively handle the fallbacks too. Once the support is available register the serviceWorker.js
Copy this code to the bottom of your index.html page within script tags.
#2 Cache Name
Create a js file and name it serviceWorker.js. This is the one dedicated file where your whole code related to serviceworker will go.
The first thing is to give cachename a name. This is important as , SW is all about programmable network proxy. So, we can control what we want to do when there will be request for files.
Important: You need to update the cachename everytime you are doing changes in serviceWorker.js
At line number 2 I have put all my files I wanted to be cached. It is an Array. You can put your files there.
Tip: Start with index.html, css file and offline.html (this will hold the message you are offline).
#3 Install
Once the serviceworker is available on browser and serviceWorker.js file is registered. The next thing we will do is install. This happen only once. It also open the cache and add all the files we have mentioned in the filelist. At this step we made our own cache.
#4 Activate
Once your cache is ready the next event is to activate it. A service worker won’t receive events like fetch
and push
until it successfully finishes installing and becomes "active".
#5 Fetch
Here is the magic take place. When the user request for pages. The service worker’s fetch event will monitor each request and check against the cache that what we have to do when some cached file is requested. Fetch event take the decision the requested files need to server from the server or from the cache.
Also, when there is no network, Fetch event take care which all files needed to serve to the user. Hence controlling the offline request too.
Browser support
2 years ago, Chrome was the only browser which was supporting Service workers but now most of the browsers have the support.
Check here
In the next post we will see how to pull all together and how to implement SW in application. If you liked do give clap. Do share your thoughts.
Follow me at twitter.com/hellonehha