Service Worker
A service worker, while being called a worker, is quite different from dedicated and shared worker. It serves as a proxy between the client-side web application and the server.
There are three stages in the lifecycle of a service worker:
- Download: The browser downloads the service worker from the remote server.
- Install: The browser installs the downloaded service worker, which triggers the
install
event in the service worker. - Activate: The service worker is actively running. It will be updated only up on request (i.e., an event is fired on the service worker) and it has not been downloaded in the last 24 hours.
We use a simple example to illustrate service worker. The example dies two thigs
- it intercepts the HTTP request from client web page and returns a constant string for a certain request.
- it adds a specific json file to the cache.
Main thread code:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./worker.js', {scope: './'})
.then((reg) => {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch((error) => {
// registration failed
console.log('Registration failed with ' + error);
});
}
fetch("./msg.json")
.then(response => response.json())
.then(data => console.log(data));
Service Worker Code:
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll([
'./test.json'
]);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
event.request.url.match("./msg.json")
? new Response('{"message":"Hello from Service Worker"}', {headers: { 'Content-Type': 'application/json' }})
: fetch(event.request)
);
});