Last Updated on
July 5, 2024

What is a Service Worker and why are they Important?

Published in
Key takeaways:

Service workers are a crucial piece of web infrastructure that enable web push notifications (and other things). 

In this article we will explain what service workers are, how they work, and everything you need to know to deliver winning push campaigns to your users and customers. 

Let’s begin. 

What is a Service Worker?

At the simplest level - a service worker is a JavaScript file that runs separately from the main web page, and acts as a middle “layer” between browser and server. They are often described as proxies between web browsers and servers. 

This is important because it allows you to control certain aspects of your web app’s functionality even when the user is not actively browsing the site

The service worker runs background processes and can perform tasks independently of the web page itself.

What do Service Workers Do? 

Service workers enable powerful features across web apps, like: 

  • Offline functionality
  • Background synchronization
  • Push notifications

They’re an essential part of Progressive Web Applications (PWAs), playing a crucial role in their success and strong UX. 

Now we’ve introduced service workers, let’s go into a bit more depth about how they work on a high level. 

The Service Worker Lifecycle

When a web user comes into contact with a website that has service worker code, a series of steps occur.

These are known as the service worker “lifecycle”, and understanding it is important for understanding service workers in general.  

  1. Registration: When a user first visits a website with a service worker, their browser becomes aware and “registers” it. This is automatic, the user won't notice anything, and no permissions are needed. 
  1. Installation: As the user interacts with the site or web app, the service worker starts caching certain parts of the website - for example images, scripts, and stylesheets). This again occurs without the users’ involvement, and allows for both faster loading on repeat visits and also offline functionality. 
  1. Activation: Once the service worker has successfully saved the necessary resources, it becomes active. The service worker takes control, replacing any older version, and manages cached resources to ensure the user accesses the most recent and relevant content.
  1. Idle: Now that the service worker is active, it waits in the background. As the user continues browsing, the service worker is ready to respond to any requests, such as loading content from the cache.
  1. Fetch/Functional: If the user makes a request (like clicking on a link or loading an image), the service worker decides whether to fetch the content from the cache or the internet. If the user is offline or on a slow network, the service worker can serve content from the cache, ensuring the website remains accessible and fast.
  1. Termination: If the browser needs to free up resources, it might stop the service worker when it's not in use. But it can quickly restart the service worker when needed, and the user won't notice this happening in the background.
  1. Update: On subsequent visits to the website, if the browser detects any changes in the service worker's code, it will start the process of installing and activating the new version. This ensures that the user always experiences the most up-to-date version of the website.

So that’s the service worker lifecycle. Throughout this process the user’s experience is smooth, with the service worker operating in the background. Now, are you starting to see why service workers are so powerful? 

Let’s look at a few of the key functionalities they enable. 

The Role of Service Workers in Web Applications

For modern web apps, service workers are crucial for key parts of their UX, helping them to perform and feel closer to native apps than ever. 

Three key functionalities they enable are: offline functionality, background sync, and push notifications. 

We’re going to specifically focus on push notifications, but let’s briefly cover the other two first. 

How Service workers enable offline functionality

By caching key resources like HTML, CSS, JavaScript, and images, service workers allow users to access and interact with web apps even when they are offline or experiencing a poor network connection.

Recall that when a user visits a site for the first time, the service worker caches necessary files and data. 

Subsequent visits to the app can then be served from the cache, reducing the reliance on the network and allowing the user to interact with the site with low or even zero internet connection. 

How service workers enable background sync

Another valuable feature enabled by service workers is background sync. Background sync allows web applications to synchronize data with the server, even if the app is not currently open, the device is offline, or the user has a poor internet connection. 

It ensures that any actions taken, or data entered, by users will be synced and processed once they come back online. 

For example, if a user submits a form while offline, the service worker can capture that request and hold it in the background until a network connection is established. Once the connection is restored, the service worker will automatically send the request to the server and complete the action. 

How service workers enable Push Notifications

Now, a topic that is dear to our hearts at MobiLoud - push notifications. 

Push notifications are absolutely reliant on the capabilities of service workers to deliver timely and relevant messages to users - even when they’re not actively using your website. 

So how do service workers help out here? 

Modern browsers typically have “push services”, intermediary infrastructure that enables push notifications like Chrome’s Firebase Cloud Messaging, Windows Push Notification Services, and Mozilla’s Push Service. 

Along with the browser’s native infrastructure, there’s a lively ecosystem of third party push notification tools and services that add additional features and functionality on top. 

The service worker operates in the background, connected to but separate from your actual website or web app, and so “listens” for push events from the push service. 

Here’s how it works in more detail, step-by-step:

  1. Permission: the user grants you permission to send notifications 
  2. Registration: The service worker is registered on the user's device, allowing it to run independently in the background
  3. Subscription: The service worker requests a subscription object from the browser push service, which then creates a unique endpoint (or address) for the specific user device. This endpoint, along with some other data, forms the subscription object.
  4. Sending Notifications: When you want to send a push notification, your server sends a request to the push service associated with the user’s browser, addressed to the unique endpoint created in the previous step. The push service then communicates directly with the user’s device.
  5. Displaying the Notification: the service worker, always on standby, listens for incoming push events. When a push message is received, the service worker processes the data and uses the browser's Notification API to display the notification to the user, regardless of whether they have the website open.

And voila, your message is sent. This may seem like a laborious process, but it’s all largely automated and not too complex to add to your site. 

Implementing Service Workers

In this section we’re going to run through the process of registering a service worker, handling push notifications, & the best practices to ensure successful implementation.

Registering a Service Worker

The first step in implementing service workers is to register them in your web app. 

Just to recap - a service worker is a JavaScript file that runs in the background, separate from the main web page. It acts as a proxy between your web application and the user's browser, enabling features such as push notifications and offline functionality.

Here’s an example of some code to register a service worker on your site, either within <script> tags in your main HTML file or more likely within an external Javascript file ie main.js:

As you can see above, the code checks if the browser supports service workers and then registers the service worker by providing the path to the JavaScript file. 

Once registered, the service worker is installed and ready to handle events and perform tasks in the background.

Registering a service worker is pretty much that simple! But remember, the real power of service workers is in configuring it to work optimally for your own site and users. 

Handling Push Notifications

Speaking of configuring service workers, let’s see a brief example of how to start handling push notifications. 

To handle push notifications, you need to have your service worker “listen” for the push event:

In this code, the push event is triggered when a push notification is received from the browser push service. 

The event data contains the notification payload, which can include the title, body, and other customizable options. 

The service worker then uses the showNotification method to display the push notification to the user.

Note: If you’re new to web development, learning the following definitions will help you understand this topic (and many others) on a deeper level:

Service worker best practices

To ensure a successful implementation of service workers, here are a few best practices that you (or your developer) should keep in mind: 

  • Test Across Browsers: While most modern browsers support service workers, there can be nuances in behavior and implementation. Ensure you test on all major browsers to guarantee consistent functionality.
  • Handle Errors Gracefully: Service workers operate in the background, and unexpected situations can arise. Implement robust error handling mechanisms to manage such scenarios without disrupting user experience.
  • Keep Service Workers Updated: As you refine your web app, ensure your service worker is also updated to reflect those changes. Increment the version number or change the service worker file's contents to trigger updates.
  • Consider User Permission: For features like push notifications, always seek explicit user permission before subscribing them. Ensure that your approach respects user privacy and adheres to relevant regulations and best practices.
  • Cache Strategically: Decide on a caching strategy that fits your web app's needs, such as cache-first or network-first. Periodically review and clean your cache to make sure everything is efficient.
  • Stay Informed: The web is ever-evolving, and best practices can change. Stay updated with the latest advancements and changes related to service workers and the broader web platform.

By following these best practices, you’ll be set up to leverage service workers to their full potential. 

Are web notifications enough? 

Even though service workers can help to transform your web app and send notifications to users' devices, web notifications in general have their downsides. 

Native app notifications are an entirely different category that do not use service workers in any way. They have several advantages over web notifications:

  • Higher opt-in and engagement rates
  • Better for reaching iOS users
  • Better for personalisation

You can read more in this comparison.

Native app notifications are the clear winners except for one thing - traditionally it was expensive and difficult to build native apps. It took months of labour and a six figure investment.

Luckily, that isn’t true anymore.

With MobiLoud, you can get native apps in just weeks, for a small fraction of the usual cost.

You’ll be able to keep every feature and functionality of your web app - and also to send unlimited push notifications to users, no matter their mobile OS!

We specialise in building apps for ecommerce, and power the apps of thousands of brands including multibillion dollar multinationals.

Check out some of our app examples

We give you everything you need to leverage push - including abandoned cart notifications, A/B testing, and more. Want to learn more about MobiLoud? Get started with a free preview of your app, or schedule a free, personalized demo and get a first-hand look at the platform's possibilities with one of our app experts.

Getting back to the web - we hope this article has helped to inform you about service workers.

Good luck with implementing them on your website.

Convert your website into a mobile app

Get custom mobile apps for iOS and Android that update automatically with your site and work with your entire tech stack.
Jack & Jones logo.Bestseller's logo.John Varvatos logo.
John Varvatos iOS push notification

Read more posts like this.