Service Workers in Javascript
Last Updated :
30 Aug, 2019
What is Service Worker:
A service worker is a script that runs independently in the browser background. On the user side, it can intercept its network requests and decide what to load (
fetch).
Service workers mainly serve features like background sync, push notifications and they are commonly used for'offline first' applications, giving the developers the opportunity to take complete control over the user experience.
Before it's time there has been API called
AppCache, which has been trying to serve the offline experience feature. However, there have been numerous problems in the interface of the
AppCache API and Service Workers are here, going over them.
The service worker life cycle:
The service worker lifecycle is completely separate from the web page. It's a programmable network proxy, which is terminated when it's not used and restarted when it's next needed. Service Workers heavily rely on the use of
Javascript Promises , so it's good to go over them if they are new to you.
During installation, the service worker can cache some static assets like web pages. If the browser cache the files successfully, the service worker gets installed.
Afterward, the worker needs to be activated. During activation the service worker can manage and decide what to happen to the old caches, typically they are being deleted and replaced with the new versions.
Lastly, after activation, the service worker takes control over all pages in his scope,
without the page which initially registered the service worker, which needs to be refreshed. The service worker is smart in terms of memory usage and will be terminated if there is nothing to fetch and there are no message events occurring.
Below is a picture of the place of a service worker between the browser and the network.
The website request chain using Service Worker.
Prerequisites :
- HTTPS unless on localhost
- Service workers require the use of HTTPS connection. Before deployment, the workers does work under the localhost server but if you want to upload it to the internet you need to have the HTTPS setup on your server. One good place to host free demos are the GitHub Pages, which are server over HTTPS.
- Browser support
- Service Workers are highly supported over the internet by Chrome, Firefox, Opera, Safari and Edge, which makes them worthy for deployment.
Registration:
To set up a service worker it needs to be registered. This is done in your page's Javascript. Once a service worker is registered this will cause the browser to start installing it in the background.
javascript
// Ensure that the browser supports the service worker API
if (navigator.serviceWorker) {
// Start registration process on every page load
window.addEventListener('load', () => {
navigator.serviceWorker
// The register function takes as argument
// the file path to the worker's file
.register('/service_worker.js')
// Gives us registration object
.then(reg => console.log('Service Worker Registered'))
.catch(swErr => console.log(
`Service Worker Installation Error: ${swErr}}`));
});
}
Installing:
After the service worker gets registered it needs to be installed, this is done in the service worker file and where you typically want to fetch your cache assets.
The following steps need to be taken:
- Open a cache
- Cache the assets
- Confirm if the caching is successful
javascript
var cacheName = 'geeks-cache-v1';
var cacheAssets = [
'/assets/pages/offline-page.html',
'/assets/styles/offline-page.css',
'/assets/script/offline-page.js',
];
// Call install Event
self.addEventListener('install', e => {
// Wait until promise is finished
e.waitUntil(
caches.open(cacheName)
.then(cache => {
console.log(`Service Worker: Caching Files: ${cache}`);
cache.addAll(cacheAssets)
// When everything is set
.then(() => self.skipWaiting())
})
);
})
Activating:
javascript
// Call Activate Event
self.addEventListener('activate', e => {
console.log('Service Worker: Activated');
// Clean up old caches by looping through all of the
// caches and deleting any old caches or caches that
// are not defined in the list
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(
cache => {
if (cache !== cacheName) {
console.log('Service Worker: Clearing Old Cache');
return caches.delete(cache);
}
}
)
)
})
);
})
Fetching event:
Once the service worker is set up, it should start to interact and use the cached responses. When a particular user navigates through the web pages, the service worker begins to receive
fetch events. The following example demonstrates a case when the worker receives a fetch event and search for a matching cache if there is one, it returns the cached file/value, otherwise, it returns the default response of the call to
fetch
javascript
var cacheName = 'geeks-cache-v1';
// Call Fetch Event
self.addEventListener('fetch', e => {
console.log('Service Worker: Fetching');
e.respondWith(
fetch(e.request)
.then(res => {
// The response is a stream and in order the browser
// to consume the response and in the same time the
// cache consuming the response it needs to be
// cloned in order to have two streams.
const resClone = res.clone();
// Open cache
caches.open(cacheName)
.then(cache => {
// Add response to cache
cache.put(e.request, resClone);
});
return res;
}).catch(
err => caches.match(e.request)
.then(res => res)
)
);
});
Service Worker can't:'
Access the Parent Object
Access the Window Object
Access the Document Object
Access the DOM
However, the Service Worker can:
Cache Assets & API calls
Manage Push Notifications
Control the Network Traffic
Store the Application Cache
Common use cases:
Offline-optimized experience
Sending Push Notifications
Background sync
Reference: https://developers.google.com/web/fundamentals/primers/service-workers/
Similar Reads
How to Manage Service Worker Cache in JavaScript?
A service worker's ability to cache resources is crucial for a performant and reliable web application. By storing frequently accessed files like HTML, JavaScript, and images, you can enable offline functionality and faster loading times. Below are the approaches to manage service worker cache in Ja
3 min read
How JavaScript Works?
JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f
13 min read
Working with APIs in JavaScript
An API is simply a medium to fetch or send data between interfaces. Let's say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint. This is made possible by the API or the Applica
5 min read
String in DSA Using JavaScript
A string in JavaScript is a sequence of characters enclosed in single ('), double ("), or backticks (`). Strings in JavaScript are immutable, meaning their contents cannot be changed after creation. Any operation that modifies a string actually creates a new string.Example:JavaScriptlet s = "GfG"; c
2 min read
JavaScript JSON Parser
JSON (JavaScript Object Notation) is a popular lightweight data exchange format for sending data between a server and a client, or across various systems. JSON data is parsed and interpreted using a software component or library called a JSON parser. Through the JSON parsing process, a JSON string i
3 min read
Getting Started with JavaScript
JavaScript is a lightweight, single-threaded, dynamically typed, interpreted programming language with object-oriented capabilities. Primarily JavaScript is used to add interactivity and dynamism to web pages. It breathes life into static HTML and CSS, enabling features like dynamic content updates,
8 min read
JavaScript Promise Reference
JavaScript Promise is used to handle asynchronous operations JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code. Promises are the ideal choice for handling asynchronous operations in the simples
2 min read
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipula
2 min read
JavaScript Requests
In JavaScript, there are many different ways to send the request to a server or database from the front end of an application. Here's a quick reference to all the methods to send a request using JavaScript. These are the following approaches to creating a request: Table of Content JavaScript XMLHttp
3 min read
How to Stream Response in JavaScript?
Streaming responses in JavaScript refers to the process of handling data from a server in chunks as it arrives, rather than waiting for the entire response to be received before processing it. This can be particularly useful for handling large datasets, real-time data, or improving the perceived per
3 min read