What exactly is a service worker?
At the basic level, a service worker is a script that runs independently of your app, meaning it can continue to run after the user closes the app, while providing new, network-based, functionality to your app. This new functionality includes programmatically controllable caching, background sync, and push notifications. Service workers are currently supported in Chrome, Firefox, and Opera and are actively being implemented in Edge.
Most likely, when you first hear about service workers, you’ll hear about them in the context of caching. They allow you to give your PWA an offline experience by programmatically control caching resources. The older App-Cache API was similar, but was not controllable and only allowed you to list assets you would like cached.
Service workers allow you to implement different types of caching, such as pre-caching and read-through caching. This allows you to build an offline experience for users that is tailored to the functionality your app provides, instead of just a one-size-fits-all experience. For a good example of the offline ability that service workers provide, you can check out our Ionic 2 PWA demo Hodi, a video chat PWA that will load even when offline or on bad connectivity!
Other cool things service workers enable
Background sync allows you to “save” an action until a user has connectivity and then fire off that event. An example of this can be found on the emojoy PWA by Jake Archibald. If you’re offline and send a message, the service worker will defer the actual sending of that message until you have regained connectivity.
Web push notifications are a standards-based way to send push notifications from a web app. This is a feature that has been painfully missing from the web for a while, and with service workers, we now have this power! For an example, you can either check out emojoy or another Ionic 2 PWA demo, AnonChat. These apps both send push notifications when a new message is received, even when the app is fully closed!
As you can see, service workers enable a whole new level of experiences on the web that allow you to bring your users awesome new functionality. The future of service workers in Ionic is very bright, with our eventual goal being to make it completely painless to enable a service worker for your Ionic 2 PWA. Join the revolution today and make your next Ionic 2 PWA network-independent!