There are common scenarios in which web applications are limited by not having an active window tab in the Web browser. However, if we take our app to the mobile world, this limitation does not exists, because even though a mobile app is closed, we can interact with the user by using, for example, push notifications. Service workers are the best option for adding special capabilities to web apps, which make them feel natural when they are installed from a mobile device (without users having to “enter” an app store or Google Play).
The Web is evolving. We can now create mechanisms that give users similar experiences in both apps and browsers, which led to the development of PWAs and service workers.
What Is a Service Worker?
Service workers cannot access the document object model (DOM ) directly. Service workers communicate with the pages that they control through the PostMessage interface, which manipulates the DOM if needed.
With service workers, we can control how network requests are handled.
Service workers store information through IndexedDB, which I mentioned earlier. IndexedDB is a transactional database system found in web browsers. What do I need to use a service worker?
- 1.
Web browser support. You can see the actual support here: https://caniuse.com/#feat=serviceworkers
- 2.
HTTPS in the server (except in localhost)
Understanding the Life Cycle
Installing: This is the first event that occurs. It is given just one time per service worker. If the called promise in this event fails, the web browser does discard it and won’t let that the service worker take control of the client.
Activated: After the service worker controls the client and is ready to handle events, the activated state is initiated. The service worker is now active.
Terminated and Fetch/Message : After the service worker is in control of the pages, it can be in one of two states: terminated (to save memory) or fetch/message (to handle network requests).
Adding a Service Worker to an App
- 1.
Create a JS file, sw.js, and locate it in the web project root (normally at the same level of the main entry). In Vue projects, we need to move this file to the public/ folder, because when we make a build, our tool takes this folder as our web app root.
- 2.
Register the service worker by adding the following:
Core Technologies
Service workers allow adding new functionality thanks to some core technologies. We look at them next.
Promises
pending: Initial state
fulfilled: The operation completed successfully
rejected: The operation failed
We use promises in each application programming interface (API) that we integrate into our script, which is why we must have a good understanding of this concept.
Fetch API
The fetch API is a new web interface that seeks to simplify XMLHttpRequest and provides more features that help the resource search through the network.
As you can see, it works like a promise and allows for easy response management. In addition, thanks to its request and response objects, we have good control over the requests we intercept from the network.
Cache
Saving files locally is one of the most important advantages offered by PWAs. Let's think about that for a moment.
Mobile phone users often find themselves with very bad connections, such as when they are on a subway or when they are in a basement. Users just want to have a good experience with our services, which is why we need the cache API and the cache storage API to store important files locally, and respond with the app shell on all occasions. In this way, users don’t have to wait for the PWA UI to load when they have an unstable connection.
cache.addAll(): Adds an element array to cache storage.
cache.delete(): Deletes an element from cache storage.
cache.match(): Gets the first element that matches the sent parameter. If it is unable to find one, it sends an undefined.
cache.put(): Allows for the addition of a new element to the cache.
Debugging Our Service Worker
Summary
A service worker is a JS file that executes in the background, regardless of whether a web site is open. Thanks to service workers we can add support to a new world of Web APIS like CacheStorage and can use offline features to improve the user interaction with our Apps.