Ever wondered why some websites seem to keep working even when you’re offline? The secret is simple. These websites have service workers.
Service workers are the key technology behind many native app-like features of modern web applications.
What is a service worker?
A service worker is a special type of JavaScript web worker. A service worker is a JavaScript file that acts like a proxy server. Allows you to catch network requests sent by your application and create custom responses. For example, you can serve cached files to users when they are offline.
Service workers also allow you to add features such as background synchronization to your web application.
Why Choose Service Worker
Web developers have long sought to extend the functionality of their apps. Before Service Workers, you could use a variety of solutions to make this possible. Of particular note is AppCache, which makes caching resources useful. Unfortunately, it had the problem of being impractical for most apps.
AppCache seemed like a good idea as it makes it very easy to specify which assets to cache. However, when I made a lot of assumptions about what I was trying to do and the app didn’t follow those assumptions exactly, it broke horribly. For more information, see Jake Archibald’s (unfortunately well-titled but well-written) Application Cache is a Douchebag. (Source: MDN)
Service Workers are the current attempt to remove the shortcomings of technologies like AppCache to ease the limitations of web apps.
Use cases for Service Workers
So what exactly does a service worker do? A service worker lets you add functionality to your web application that is characteristic of native apps. It can also provide a normal experience on devices that don’t support Service Workers. Such apps are sometimes called Progressive Web Apps (PWA).
Here are some of the features Service Workers enable:
- Allows users to continue using your app (or at least parts of it) even when they’re not connected to the internet. Service workers accomplish this by serving cached assets on request.
- In Chromium-based browsers, service workers are one of the requirements for making web apps installable.
- A service worker is required to enable a web application to implement push notifications.
Service worker lifecycle
A service worker can control requests for an entire site, or just some of the pages on the site. A given web page can have only one active service worker, and all service workers have an event-based lifecycle. A service worker’s lifecycle generally looks something like this:
- Register and download workers. A service worker’s life begins when a JavaScript file registers the service worker. After successful registration, the service worker will download and start running in a special thread.
- When a page controlled by a service worker loads, the service worker receives an “install” event. This is always the first event the service worker receives, and you can set listeners for this event within the worker. The “install” event is typically used to fetch and/or cache resources needed by the service worker.
- Once the service worker has finished installing, it will receive an ‘activate’ event. This event allows workers to clean up redundant resources used by previous service workers. If you’re updating a service worker, the activate event will only fire if it’s safe to do so. This is when no page is loaded that still uses the older version of the service worker.
- The service worker will then have full control over all pages loaded after being successfully registered.
- The final phase of the lifecycle is redundancy. This happens when a service worker is removed or replaced with a newer version.
How to use Service Workers in JavaScript
The Service Worker API (MDN) provides an interface for creating and manipulating service workers in JavaScript.
The first thing you need to do to create a service worker is navigator.serviceWorker.register() Method. It looks like this:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
console.log('Service worker registration succeeded:', registration);
}).catch((error) => { console.log('Service worker registration failed:', error); });
} else {
console.log('Service workers are not supported.');
}
The outermost if block performs feature detection. Ensure that service worker-related code only runs on browsers that support service workers.
Then the code is register Method. Pass the path to your service worker (relative to your site’s origin) to register and download it.of register Methods also accept an optional parameter called scope. This can be used to limit the pages controlled by a worker. A service worker controls all pages of an application by default.of register The method returns a Promise indicating whether the registration was successful.
Once the promise is resolved, the service worker is successfully registered. This code then prints to the console an object representing the registered service worker.
If the registration process fails, the code will catch the error and log it to the console.
Here’s a quick example of what the service worker itself might look like:
self.addEventListener('install', (event) => {
event.waitUntil(new Promise((resolve, reject) => {
console.log("doing setup stuff")
resolve()
}))
console.log("Service worker finished installing")
})self.addEventListener('activate', (event) => {
event.waitUntil(new Promise((resolve, reject) => {
console.log("doing clean-up stuff!")
resolve()
}))
console.log('activation done!')
})
self.addEventListener('fetch', (event) => {
console.log("Request intercepted", event)
});
This demo service worker has three event listeners registered against itself. There is his one for ‘install’ event, ‘activate’ event and ‘fetch’ event.
Within the first two listeners, the code is wait until Method. This method accepts a Promise. Its job is to make sure the service worker waits for the promise to be resolved or rejected before moving on to the next event.
A fetch listener fires whenever a request is made to a resource controlled by the service worker.
Resources controlled by a service worker include all pages controlled by the service worker and all assets referenced by those pages.
Power your web app with Service Workers
A service worker is a special kind of web worker that serves its own purpose. Precedes network requests to enable features such as offline app access. Using Service Workers in your web application can greatly improve the user experience. You can use the Service Worker API to create service workers and interact with them.