Working with service workers
Service workers provide the magic behind PWAs. They are used for caching, background syncing, and push notifications. A service worker is a JavaScript file that intercepts and modifies navigation and resource requests. It gives us full control over which resources are cached and how our PWA behaves in different situations.
A service worker is simply a script that your browser runs in the background. It is separate from the app and has no Document Object Model (DOM) access. It runs on a different thread than the thread used by the main JavaScript that powers your app, so it is not blocking. It is designed to be fully asynchronous.
Service worker life cycle
When working with service workers, it is very important to understand their life cycle because offline support can add a significant amount of complexity to the web app. There are three steps in the life cycle of a service worker—install
, activate
, and fetch
, as illustrated in the following diagram...