Service Worker

Naga Durga
4 min readJun 12, 2017

--

service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction.

Why Should I Use ServiceWorker

There are three main situations where the service will helpful Offline applications, Performance and Notifications.

Offline Applications

To build an offline application either we can use caching headers or app cache.

Caching headers allows you to how long the browser should hold content. Whenever you send a request first it will checks header if the header contains cache information it will serve from the cache only without making server call.

In AppCache there is a manifest file containing a detailed list of resources that the browser should store offline. If you make a mistake listing a resource, nothing is cached offline and content will only be updated if the manifest file itself changes.

By using service worker you can build offline applications easily. User opens browser and enters the site address on that time the service worker will installed and it will start caching the resources, if user connectivity fails still the user can able to access the site and also able to see the previously visited pages.

Perfomance

Service worker could be used to speed up a user’s browser experience by downloading resources and caching them locally.

offline-cookbook this book will clearly explain about different ways of caching and how you can make use of cache.

Advantages

  • It allows you to building offline web applications in a natural way.
  • It gives complete control over to developers. It gives you control over caching and how requests are handled.
  • By using service worker you can send notifications to the user of specific events occurring in the background when combined with other APIs.
  • Service worker is a programmable network proxy, allowing you to control how network requests from your page are handle
  • It can terminate when it isn’t in use, and run again when it’s needed (i.e., it’s event-driven)
  • To run service worker you need HTTPS

Why HTTPS

Service worker is developer friendly, it gives full control over to developers. Using service workers you can hijack connections, respond differently, and filter responses.

While you would use these powers for good, a man-in-the-middle might not. To avoid this, you can only register for service workers on pages served over HTTPS, so we know the service worker the browser receives hasn’t been tampered with during its journey through the network.

Life Cycle

The service worker lifecycle includes 6 different event types:

  1. install
  2. activate
  3. fetch
  4. message
  5. sync
  6. push

Register

To install a service worker, you need to register it, registering a service worker will cause the browser to start the service worker install step in the background.

create a serviceWorker.js file in the root directory of your application and update it as below:

if (‘serviceWorker’ in navigator) {
window.addEventListener(‘load’, function() {
navigator.serviceWorker.register(‘serviceWorker.js’)
.then(function(registration) {
console.log(‘Registration successful‘);
}, function(err){
console.log(‘Registration failed: ‘, err);
});
});
}

You can call register() every time a page loads the browser will figure out if the service worker is already registered or not and handle it accordingly.

Install and activate

After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site.

The install event is fired when an install is successfully completed. The install event is generally used to populate your browser’s offline caching capabilities with the assets you need to run your app offline.The install event is fired when an install is successfully completed.

To do this, we use Service Worker’s brand new storage API cache a global on the service worker that allows us to store assets.This API works in a similar way to the browser’s standard cache, but it is specific to your domain. It persists until you tell it not to persist, you have full control.

self.addEventListener(‘install’, function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log(‘Opened cache’);
return cache.addAll([
'index.html',
'style.css'
etc..
]);
})
);
});

cache.open() will takes name as an argument and it will opens a cache with that name. cache.addAll() will takes an array of files as an argument and it will add them cache.event.waitUntil() will wait until all the promises get to resolved.

If all that files cached successfully then only the service worker will be installed. If any of the files are failed to cache then the service worker won’t be installed.

Caching and Returning data

self.addEventListener(‘fetch’, function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response;
}
return fetch(event.request);
})
);
});

Whenever user navigate between different pages the service worker will checks whether the requested data is in cache it will return response.

If the requested data is not available in cache it will make a network request and return the data. If we want we can cache the response.

--

--