Working with Service Workers
Learn the basics of service workers and how to use them.
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 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 the 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:
Install
During the install step, the service worker usually caches some of the static assets of the website, such as an offline splash screen. If the files are cached successfully, the service worker is installed. However, if any of the files fail to download and cache, the service worker is not installed and does not move to ...