Service Workers

ashima mahajan
2 min readJan 12, 2021

A service worker is a browser API. It is a script which runs in background by the browser that allows you to cache the assets, handle push notifications, background sync and more. With the help of service workers you can make your page available even if you are offline.

Some points about service worker:

  • It is a network proxy. It intercepts the calls being sent from your page.
  • It runs in worker context, on a thread different from main JS thread and hence it cannot access DOM. But it can communicate with your page through messages and then your page can handle DOM manipulations.
  • Since it runs on a separate thread, it is non blocking.
  • It is async in nature and makes heavy use of promises.
  • It has access to IndexedDB API.

You can use service worker in localhost or with https in your server. It does not run on http for security reasons.

Life cycle of service worker

  1. Register: You need to register a service worker from your JS page. You normally maintain a separate file dedicated to service worker. In the example below, we are using sw.js file present at the root of your app.
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(
function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful');
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
}
);
});
}

2. Install: This will make browser to start installation process (if service worker not already installed for your page) in the background. This gives you the room where you can decide what you want to do during this installation step. Typically, you cache the static assets of your page.

You can listen to install event and in the callback, write a code to cache the files.

const CACHE_NAME = 'cache-v1';
const urlsToCache = [
'/',
'/styles/main.css',
'/script/main.js'
];

self.addEventListener('install', (event) => {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});

3. Activate: After installation, it enters activation phase where you can manage your old caches. For example, if you change your service worker file (sw.js here), the browser will identify it and it will install new service worker. The old service worker will be killed on next page reload (basically, when there are no longer any pages loaded that are still using the old service worker) and new service worker will take control and its activate event will be fired. In the activate callback, if you don’t want old cache anymore, you can delete it.

4. After activation step, service worker can now handle the fetch requests going from your page. You can listen to fetch event.

self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
// send network request if not found in cache
return fetch(event.request);
}
)
);
});

--

--