Sometimes we may hear of Service Workers, about all the things they can do for us including some heavy lifting work. So in these blog series, we are looking at what Service Worker is and how we can “hire” one to help our websites.
What is a service worker
Based on Google Dev, a service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction. Today, they already include features like push notifications and background sync.
The reason this is such an exciting API is that it allows you to support offline experiences, giving developers complete control over the experience. Before service worker, there was one other API that gave users an offline experience on the web called AppCache.
Things to note about a service worker:
- It can’t access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM instead.
- Service worker is a network proxy, allowing you to modify requests and responses, replace them with items from its own cache, and more.
- It’s terminated when not in use, and restarted when it’s next needed. If there is information that you need to persist across restarts, service workers can use the IndexedDB API.
- Service workers make extensive use of promises.
Use cases
- Caching strategies
- Web push
- Offline handling
- API Analytics: perform API usage logging without interfering with the UI layer by adding a service worker to gather the usage and use the sync API to upload gathered data from time to time.
- Load balancer: Service Worker containing network logic to dynamically select the best content provider accordingly to server availability.
- Dependency Injection: This recipe shows how a Service Worker can act as a dependency injector, avoiding hard wiring dependencies for high level components.
Interfaces
Cache :
Represents the storage for Request
/ Response
object pairs that are cached as part of the ServiceWorker
life cycle.
Cache.match(request, options)
Returns a Promise
that resolves to the response associated with the first matching request in the Cache
object.
Cache.matchAll(request, options)
Returns a Promise
that resolves to an array of all matching requests in the Cache
object.
Cache.add(request)
Takes a URL, retrieves it and adds the resulting response object to the given cache. This is functionally equivalent to calling fetch()
, then using put()
to add the results to the cache.
Cache.put(request, response)
Takes both a request and its response and adds it to the given cache.
Cache.delete(request, options)
Finds the Cache
entry whose key is the request, returning a Promise
that resolves to true
if a matching Cache
entry is found and deleted. If no Cache
entry is found, the promise resolves to false
.
Cache.keys(request, options)
Returns a Promise
that resolves to an array of Cache
keys.
Client
Represents the scope of a service worker client. A service worker client is either a document in a browser context or a SharedWorker
, which is controlled by an active worker.
Clients
Represents a container for a list of Client
objects; the main way to access the active service worker clients at the current origin.
Navigator.serviceWorker
Returns a ServiceWorkerContainer
object, which provides access to registration, removal, upgrade, and communication with the ServiceWorker
objects for the associated document.
ServiceWorker
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker
object.
A ServiceWorker
object is available in the ServiceWorkerRegistration.active
property, and the ServiceWorkerContainer.controller
property — this is a service worker that has been activated and is controlling the page.
The ServiceWorker
interface is dispatched a set of lifecycle events — install
and activate
— and functional events including fetch
. A ServiceWorker
object has an associated ServiceWorker.state
, related to its lifecycle.
ServiceWorker.state
Returns the state of the service worker. It returns one of the following values: installing
, installed,
activating
, activated
, or redundant
.
ServiceWorkerGlobalScope
interface of the ServiceWorker API represents the global execution context of a service worker.
- Properties
ServiceWorkerGlobalScope.clients
:Contains the Clients
object associated with the service worker.
ServiceWorkerGlobalScope.registration
Contains the ServiceWorkerRegistration
object that represents the service worker's registration.
ServiceWorkerGlobalScope.caches
Contains the CacheStorage
object associated with the service worker
- Events
activate && fetch && install && message
Occurs when incoming messages are received. Controlled pages can use the MessagePort.postMessage()
method to send messages to service workers. The service worker can optionally send a response back via the MessagePort
exposed in event.data.port
, corresponding to the controlled page. Also available via the ServiceWorkerGlobalScope.onmessage
property.
Life cycle
That’s so much of it. Next post we are looking at examples of how to initialise and get a service worker up and running.
Happy Reading!