A service worker is a new API that allows you to run a script in background of your application, and facilitates creating Progressive Web Apps.
There are some key pieces of functionality that service workers allow you to implement, including:
Offlining your application: Cache assets so users can still view content when they lose their internet connection
Implementing background sync:* Allow interactions like network requests to go through at a later point in time, e.g. when you have a spotty network connection, don't send a POST request through until it's stable
Enabling push notifications*: Notify users with desktop notifications that something has happened, even if they're not currently looking at or using the application
Background sync and push notifications we'll discuss in a future lesson, but I've left an asterisk next to them because they are actually both their own separate APIs. These APIs, however, are only made possible by service workers. So although a service worker isn't solely responsible for enabling background sync and push notifications, it is the backbone and foundation of getting these features to work.
We can debug and inspect service workers for any application by navigating to the 'Application' tab in Chrome Developer Tools, and selecting the 'Service Workers' tab on the left-hand side. Take a look at all the service workers that have been registered on sites you've visited in the recent past. While this is still a relatively new API, people have clearly not been hesitant to start using them in production applications.
Code Along
Clone down this repo and run npm install then npm run start. Navigate to localhost:3000 in your browser and you should see a little markdown application. We'll code along together to add a service worker that will allow us to offline this application.
Service Workers may seem like they behave in unpredictable ways when you first start developing with them, but some clarity can be brought to this by understanding their lifecycle process.
1. Registration: browser is aware that we have a service worker that needs to be recognized, and will kick off the installation step upon a successful registration
2. Installation: the service worker is installed, but doesn’t actually control anything on the page just yet. This is a good phase to cache assets for offline use.
3. Activation: the service worker has been installed and is activated. This is a good place for us to manage old cached assets and update the service worker.
4. Full Page Control: the service worker has been activated and now has full control over any pages that fall under its scope