Table of Contents

Better Site Experience: Service Workers to Your Rescue!

Ever wondered how famous B2C sites like Twitter.com, Trivago.com, Pinterest.com, Washingtonpost.com, Plants.com, 1800flowers.com, web.whatsapp.com, and many more provide a fast, reliable, and engaging experience on mobile devices? There are multiple reasons, but one common aspect is their use of service workers.

What Is a Service Worker and How It Is Set Up

A service worker is a JavaScript file that runs in the background of a web page, acting as a proxy between the web page and the network.

 

Some use cases for service workers include:

  • Caching resources for offline use
  • Handling push notifications
  • Pre-fetching resources to improve performance
  • Background syncing of data

Below are several businesses that are reaping benefits from service workers.

Starbucks
By enabling offline access to previously viewed pages, Starbucks has been able to help customers continue browsing menus and placing orders even when they do not have a stable network.

According to PWA Stats, this has helped to

  • Double the active users
  • Increase user engagement by 23%

Twitter Lite
Service workers have helped reduce data usage, enabled offline access, and improved performance on slow or unreliable networks.

According to web. dev, this has led to:

  • 30% increment in user engagement
  • 65% increment in pages/session

Pinterest
According to this case study, service workers have resulted in:

  • 40% increment in time spent by visitors
  • 45% increment in user engagement

Trivago
According to this case study, using service workers has helped the company immensely. Impressive metrics include:

  • 150% increment in CTR (Click Through Rate)
  • 97% reduction in load time for repeat customers


The Washington Post
According to this case study, implementing service workers has helped the Washington Post:

  • Reduce load time by 88%
  • Increase return visits by 23%

 Origin of Service Workers

Before the arrival of service workers, developers only used the following techniques to improve site performance:

  • Caching: Reducing network calls by browser caching and server-side caching.
  • Asynchronous JavaScript: Loading asynchronized data without blocking the main thread.
  • Image Compression: Saving network bandwidth with Webp Image Compression.
  • Content Delivery Networks (CDNs): Storing and delivering website assets, such as images and videos, from servers closer to the user, reducing the time for loading content.

 

The techniques mentioned above, relying solely on browser-side caching or server-side loading, are undoubtedly helpful. However, when dealing with complex web applications that are feature-rich, performant, reliable, and require offline capabilities, they need extra superpowers along with the above ways.

Enter service workers – a concept born out of the necessity to enhance web applications' offline functionality.

Since service workers run in the background of a web page and intercept network requests from the browser, they enable web applications to cache content and assets locally, handle offline scenarios, and provide a more seamless and responsive user experience.

Every innovation requires time for broad adoption, and this has also been the case for service workers. Google introduced service workers in 2014 and initially implemented them in Chrome browsers. However, they needed to be integrated into a web standard to become standardized across browsers.

The specification was submitted to the W3C in 2015 for refinement and review. By 2018, service workers had been recognized as an official web standard, supported by all major browsers, as reflected in this site.

 

All major web browsers now support service workers.

Service workers have shortened the gap between web and native applications and improved developers' mindset when building new-age web applications.

Phases of Service Workers

Follow the steps below to use a service worker.

Step 1: Registration

First, you must register the service worker with the web page using the navigator.serviceWorker.register() method.

Sample Code Snippet:

*If the registration is successful, the service worker is executed in ServiceWorkerGlobalScope.
* It does not run on the main thread and has no DOM access.

Next: Ready to process events, post registration

Step 2: First EventInstallation
*The installation of a worker is attempted when in-scope pages are accessed.
*On completion of the uninstall handler, the service worker is marked as installed.

Sample Code Snippet (Install event to cache resources):

Step 3: Activation and Usage
After the installation, the activate event is fired, and its primary job is to clean up old resources used in the previous version of the worker.

Sample Code Snippet:

 

Lifecycle of Service Worker
The infographic below explains the service worker lifecycle in a simplified way.

 

A Few Chrome DevTools for Service Workers

  1. Push: We often get push notifications from native Android/iOS apps. However, the service worker feature allows web applications to receive notifications from the server, even when the application is not actively running in the browser. It displays the message as configured.
  2. Sync: Allows synchronizing data between the browser and the server, even if the web app is not running. As an example, web. WhatsApp uses the sync feature to update chats from their server.
  3. Periodic Sync: Allows to schedule regular synchronization events with the server.
  4. Update Cycle: A process by which the SW updates itself and the cache it is using.
  5. When an updated service worker is available, the browser will first download it in the background and activate it only when the current version is no longer used, thus ensuring that the app SW and cache are up to date.
  6. Chrome Service Worker Tool: When the "Bypass for network" option is enabled, the service worker will not intercept any network requests that match the specified pattern. Instead, requests will be handled without service workers.

These features provide a seamless user experience, control web applications, and ensure that data is always up-to-date and available, even when the application is not actively running in the browser.

Implementation Scenarios Around Service Workers

Scenario 1
Handling caching in a service worker

The Cache API typically handles caching. It allows you to store and retrieve responses to network requests, improving performance and enabling offline web app use.

Here is an example of how to cache resources using the Cache API in a service worker:

Two common caching strategies for handling fetch events in a service worker, if the cached response is not available, include:

  • The cache-only strategy, which always returns an error.
  • The cache-first strategy, where the service worker fetches the resource from the network and caches the response for future requests.


Scenario 2
Handling offline mode
in a service worker

In a service worker, when a network request fails due to being offline, the service worker can intercept the request and return a cached response instead.

Scenario 3
Restrict service worker access to certain URLs

The service worker has a fetch event that is called whenever a resource is requested by the browser, such as:

  • URL requested
  • Method used

Code Snippet:


Scenario 4
Handling push notifications
Client Side Code Snippet:

Server Side:

You need to use third party services like Firebase Cloud. Messaging (FCM) to set up a push notification service will forward them to your browser service worker.

Overwhelmed with Native Implementation Scenarios?

Do we have any package/library which simplifies implementation? Yes, the Workbox library by Google.

The Workbox library abstracts the initial complexity and speeds up implementation but check the below before deciding between custom implementation and Workbox.

  • Size: Workbox increases project size but depends on which modules you use.
  • Control: For specific use cases where projects need more control over service worker scenarios, go with a native implementation.
  • Maintenance: Google maintains Workbox and updates/syncs it with the latest browser updates, easing the maintainability of the code base.

Best Practices for Implementing SW


Double-check your use cases before implementing. A service worker may only sometimes be the best choice. It may not be recommended in certain instances, as seen below:

  • Static websites: A service worker may not provide significant benefits if your site is primarily static, with little to no dynamic content.
  • Desktop reliance: A service worker may be less helpful if your site is primarily accessed on desktop devices.
  • Lack of real-time updates: A service worker may not be the best choice if your site relies on real-time data, such as stock market updates or sports scores.

Remember to:

  • Refrain from caching everything. Developers often try to cache every resource, including dynamic data unsuitable for caching, leading to performance issues and increased data usage. It is essential to cache only static resources and API responses that are safe to cache.
  • Update the service worker when deploying new versions of the application. A failure to do this can lead to users seeing stale content or experiencing other issues. It is essential to update the service worker with new versions of the application.
  • Unregister the service worker when it is no longer needed is crucial. If the service worker is not correctly unregistered when it is no longer needed, it can cause user issues.

Key Takeaways

  • Service workers give superpowers to web applications like native apps.
  • Service workers are event-driven and run on a separate thread, so they have no direct access to the DOM.
  • Carefully analyze your business use cases before jumping into service worker implementation.
  • Many businesses have seen considerable improvement in user experience and site performance after empowering their sites with service workers.

 

So, what are you waiting for? Let's talk to analyze your business use case and improve your site visitor's experience.

 

Acknowledgment

This piece was written by Shubham Jain, Senior Software Engineer at Encora.

About Encora

Fast-growing tech companies partner with Encora to outsource product development and drive growth. Contact us to learn more about our software engineering capabilities.

 

 

 

 

 

 

Learn More about Encora

We are the software development company fiercely committed and uniquely equipped to enable companies to do what they can’t do now.

Learn More

Global Delivery

READ MORE

Careers

READ MORE

Industries

READ MORE

Related Insights

Online Travel Agencies: Some Solutions to changes in booking and commission attributions

Discover how we can simplify travel changes for both travelers and OTAs using blockchain and ...

Read More

The AI-Powered Journey: How AI is Changing the Face of Travel

As travel elevates itself into an experience where every journey is as unique as the travelers ...

Read More

Enhancing Operational Excellence with AI: A Game-Changer for the Hospitality Industry

By AI, the hospitality industry can offer the best of both worlds: the efficiency and ...

Read More
Previous Previous
Next

Accelerate Your Path
to Market Leadership 

Encora logo

Santa Clara, CA

+1 669-236-2674

letstalk@encora.com

Innovation Acceleration

Speak With an Expert

Encora logo

Santa Clara, CA

+1 (480) 991 3635

letstalk@encora.com

Innovation Acceleration