After the article titled “Single Page Application (SPA)”, I’d like to discuss PWA implementations that go beyond the performance and user experience approaches we’re familiar with in mobile applications.
I’ve decided to write a separate article about JavaScript Service Workers, a key component and essential feature of PWA. Therefore, without delay, let’s dive into the details of what a service worker is and what it’s used for.
JavaScript Service Workers
Service Worker is a JavaScript command that can run in the background independently of the currently displayed web page. It can also be described as a client-side proxy. By running in the background and independently of the web page, the browser (in modern browsers) gains new capabilities (service worker API1) allowing access to the web page. As the name suggests, a service worker is essentially a JavaScript worker2 defined within a specific framework. For example, they cannot access the DOM, nor can they directly intervene in user interactions. To summarize the above explanation in bullet points:
- Supported via browsers (Chrome3, Firefox4, Opera5, and Microsoft Edge6),
- Composed of a series of JavaScript operations,
- Requires an HTTPS connection (not required when using localhost).
Now, let’s explore what we can achieve with a service worker.
It is possible to ensure that when a website loses its internet connection (offline), the user’s browsing experience continues without interruption, actions performed on the web page are recorded, and these actions are then sent to the server when the internet connection is restored (background synchronization / background sync). Instant notifications (push notifications) can be sent to users directly through the browser. With the provided robust caching mechanism, performance improvements can be achieved.
Service Worker Lifecycle
I emphasize again that the Service Worker operates independently of the displayed web page and enables features to be used directly on the web page. This is because in order to use these features on the web page, certain configurations must be made.
Our first step is to indicate that the web page is working in collaboration with a Service Worker. To achieve this, we must register the Service Worker. This allows us to access browser-side features. The registration process is not affected by page refreshes; the Service Worker will be activated on the user’s next visit.
We need to create a JavaScript file that will be processed as a Service Worker. Let’s name it serviceworker.js.
if("serviceWorker" in navigator) {
navigator.serviceWorker.register('/serviceworker.js').then(function() {
console.log("Service Worker registered!");
});
} else {
console.log("Browser not supported!");
}
When we add the above code to the entry point (e.g., app.js, main.js, or index.js), the browser first checks whether it supports Service Workers. If support is available, the registration process is initiated. Upon successful registration, a message “Service Worker registered!” is displayed in the console.
The next phase consists of the service worker’s installation (install) step. During this phase, data is cached. In the event of no internet connectivity, operations continue through the data cached by the browser.
self.addEventListener("install", function(event) {
console.log("[Service Worker] Installing Service Worker...");
});
Caching is a recurring process that refreshes when a connection is established and continues until a connection is available. Different operations can be performed using Listeners. Importantly, if a change occurs in the service worker file, visitors will notice it in their browser, and as a result, the service worker will be updated.
After installation, the Activate process is performed. At this point, the service worker is fully operational. Different operations can be handled during this phase using a Listener.
self.addEventListener("activate", function(event) {
console.log("[Service Worker] Activating Service Worker...");
return self.clients.claim();
});
If the service worker is not performing any operations, it enters an Idle state. Let’s summarize the service worker’s operation:
- The service worker is defined and detected by the browser.
- The browser performs the page loading, stores the data in memory, and activates the service worker (activate) if no errors occur.
- If no operations are performed, it enters an idle state and can be restarted when needed.
Following these steps, we can optionally terminate the service worker and/or respond to messages sent via postMessage(), enabling communication with the monitored pages. These pages can also modify the DOM as needed.
Service Worker Usage
As I’ve mentioned in different sections, the most important advantage of a service worker is that it ensures the user’s experience remains intact even in cases such as a lost connection. After that, features like push notifications based on user preferences and improved performance can be highlighted. On the other hand, a web page supporting service workers can behave like an application. With a push notification (install banner), it can be added to a smart phone’s screen (Add to Home Screen) as an icon, and when this icon is clicked, it can display content in full-screen mode (without the address bar), and provide the ability to transition between screens (splash screens). Below, I’m sharing a video published by Google Chrome Developers that summarizes all of this process.
Additionally, internet connectivity monitoring can also be used for different processes, enabling customized messages (or cached different content) to be delivered to visitors. Future support for additional features such as periodic synchronization or geofencing by service workers is also expected.
Things to Keep in Mind
Service workers introduce certain additional requirements when developing web applications. Therefore, instead of fitting the entire application into a single HTML string, AJAX-style operations are preferred. This way, a container can be created that is continuously cached and can be launched even when the internet connection is lost, and content can be regularly refreshed and managed separately.
For further developments related to PWA and service workers, please refer to the following resources.
*[PWA]: Progressive Web App
- Service Workers: an Introduction
- The Basics of Web Workers
- Introduction to Service Workers
- Service Worker API
Footnotes
- Service Worker API. MDN web docs ↩
- Eric Bidelman. (2010). The Problem: JavaScript Concurrency ↩
- Matt Gaunt. (2020). Service Workers: an Introduction ↩
- Using Service Workers. MDN web docs ↩
- Bruce Lawson, Shwetank Dixit. (2016). Progressive Web Apps: The definitive collection of resources ↩
- Service Workers. Microsoft Edge Documentation ↩