An Introduction to JavaScript Service Workers

Have you ever wondered how 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 are service workers?

Service workers are a specialized type of JavaScript web worker. A service worker is a JavaScript file that functions much like a proxy server. It intercepts outgoing network requests from your application, allowing you to create custom responses. For example, you can provide cached files to the user when they are offline.

Service Technicians also allow you to add features such as background synchronization to your web applications.

Why Service Workers?

Web developers have been trying to extend the capabilities of their applications for a long time. Before the arrival of service technicians, you could use various solutions to make this possible. AppCache is particularly noteworthy, which makes caching resources handy. Unfortunately, there were issues that made it an impractical solution for most applications.

AppCache seemed like a good idea because it made it very easy for you to specify which assets to cache. However, it made many assumptions about what you were trying to do, then broke horribly when your app didn’t follow those assumptions exactly. Read Application Cache is a Douchebag by Jake Archibald (unfortunately titled but well written) for more details. (Source: DND)

Service workers are the current attempt to reduce the limitations of web applications, without the drawbacks of technologies like AppCache.

Use cases for service technicians

So what exactly do service technicians let you do? Service Workers allow you to add native application functionality to your web application. They can also provide a normal experience on devices that don’t support service technicians. Apps like this are sometimes called Progressive Web Apps (PWA).

Here are some of the features made possible by service technicians:

  • Allow the user to continue using the application (or at least part of it) when no longer connected to the Internet. Service technicians achieve this by serving cached assets in response to requests.
  • In Chromium-based browsers, a service agent is one of the requirements for a web application to be installed.
  • Service workers are required for your web application to implement push notifications.

The life cycle of a service worker

Service technicians can monitor requests for an entire site or just a portion of the site’s pages. A particular web page can only have one active service worker, and all service workers have an event-based lifecycle. The life cycle of a service worker generally looks like this:

  1. Worker registration and upload. A service worker’s life begins when a JavaScript file registers it. If the registration succeeds, the service worker downloads and then starts running in a special thread.
  2. When a page controlled by the service worker is loaded, the service worker receives an ‘install’ event. This is always the first event a service worker receives, and you can configure a listener for this event in the worker. The ‘install’ event is typically used to retrieve and/or cache any resources the service worker needs.
  3. After the service worker completes the installation, it receives an ‘activate’ event. This event allows the agent to clean up redundant resources used by previous service agents. If you are updating a Service Agent, the activate event will only fire when it is safe to do so. This is once there are no more loaded pages still using the old version of the service worker.
  4. After that, the service technician has full control of all the pages that were loaded after his successful registration.
  5. The last phase of the lifecycle is redundancy, which occurs when the service worker is removed or replaced with a newer version.


How to use Service Workers in JavaScript

The Service Worker API (MDN) provides the interface that allows you to create and interact with service workers in JavaScript.

To create a service worker, the first thing to do is to call the browser.serviceWorker.register() method. Here’s what it might look like:

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. It ensures that code related to service technicians will only run on browsers that support service technicians.

Then the code calls the Register method. It passes it the path to the service worker (relative to the origin of the site) to register and download it. The Register The method also accepts an optional parameter called scope, which can be used to limit the pages controlled by the worker. Service workers control all pages of an application by default. The Register The method returns a Promise that indicates whether the registration was successful.

If the promise resolves, the service worker has registered successfully. The code then prints an object representing the registered service worker to the console.

If the registration process fails, the code catches the error and logs it to the console.

Next, here’s a simplified 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. It has one for ‘install’ event, ‘activate’ event and ‘fetch’ event.

Inside the first two listeners, the code uses the wait until method. This method accepts a promise. Its job is to make sure that the service worker will wait for the promise to be resolved or rejected before moving on to the next event.

The fetch listener fires whenever a request is made for a resource controlled by the service worker.

The resources controlled by a service worker include all the pages it controls, as well as any assets referenced in those pages.

Improve your web applications with Service Workers

Service workers are a special type of web worker that serves a single purpose. They sit in front of network requests to enable features like offline app access. Using service workers in a web application can significantly improve its user experience. You can create service workers and interact with them using the service worker API.


Comments are closed.