Working with service workers
Service workers! They finally give developers precise control of the network layer by creating a network proxy in JavaScript. Using service workers, you can intercept and modify network resource requests, handle how caching is done, and respond appropriately when the user's network is down.
Let us show, step-by-step, how to set up a service worker and its associated methods.
Prerequisites for service workers
Prerequisites for service workers are:
- Because service workers are so powerful (almost like a network proxy) to avoid certain attacks, they're only available for domains running on HTTPS. However, they run fine on
localhost
, as well. - They heavily depend on promises, which we've already covered in depth in Chapter 4, Asynchronous Programming.
Checking for browser support
It is easy to check whether a client's browser supports service workers or not:
if('serviceWorker' in navigator) { // service worker available // lets code }
Here, I'll assume that a service...