Overview of Web Worker & Service Worker

Overview of Web Workers and Service Workers — HTML5

Life before Web-Workers,
JavaScript is single-threaded. As a result, long-lasting computations (not necessarily due to poorly written code) will block the UI thread and make it impossible to add text to text boxes, click buttons, use CSS effects, and, in most browsers, open new tabs until control has returned. This is bad for user experience(UX) and leads to frustrated for Users.

An answer to that problem is,

HTML5 Web Workers.

Web workers provide background-processing capabilities to web applications and typically run on separate threads so that JavaScript applications using Web Workers can take advantage of multicore CPUs.

HTML5 is the fifth and current major version of the HTML standard.
HTML 5 was first released in a public-facing form on 22 January 2008, with a major update and “W3C Recommendation” status in October 2014. More details on https://en.wikipedia.org/wiki/HTML5

https://en.wikipedia.org/wiki/HTML5

Let’s write our first Web worker:

First, We need to check browser support for Worker,

if (typeof(Worker) !== “undefined”) {
document.getElementById(“browser”).innerHTML =
“Your browser supports Web Workers”;
}

Now, Let's write code for our first Web Worker,

var myWorker = new Worker(‘/some/path-to-your.js’);
myWorker.onmessage = function(event) {
console.log(‘We got some data delivered!’, event.data);
};

We are creating a worker by specifying the path to our JavaScript file. In JS we will perform some intensive work (taking a load off from main thread) and once we finish we will be using a function called postMessage(data) to communicate back with the main thread. On main thread we will be using a function called onmessage() which will be listing to our worker and receives post message.

I have written one simple example, we have intensive processing with and without web worker. You can check an example here,
http://web-worker-example.s3-website-ap-northeast-1.amazonaws.com

Example: http://web-worker-example.s3-website-ap-northeast-1.amazonaws.com

More information Web APIs can be found at,
https://developer.mozilla.org/en-US/docs/Web/API/Worker

What is a Service Worker?

A 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. Today, they already include features like push notifications and background sync. With this script, you can track network traffic of the page, manage push notifications and develop “offline first” web applications.

Things to be considered:

  • With a service worker, we don't have access to the Window object, therefore, no direct access to DOM.
  • We can not run a service worker on HTTP port 80. (During development we can use localhost)

Life Cycle of Service Worker:

Now, let’s register our first Service Worker

if('serviceWorker' in navigator) {
navigator.serviceWorker
.register('bs-sw.js')
.then(function() { console.log("SW Registered"); });
}

code in our bs-sw.js file,

self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('ServiceWorkerExample').then(function(cache) {
return cache.addAll([
'/',
'/sw-index.html',
'/tool-img.png'
]);
})
);
});

This will ‘Install’ our service worker along with that we will cache the required content here at client side. You can confirm a service worker (in chrome) by inspecting a page.

Now, Let’s go “Offline” and refresh the page,

It displays “No internet” Page. To make our page available “offline” we need to intercept the fetch() call using service worker and fetch the cached contents. To do so add the following code in bs-sw.js file,

self.addEventListener('fetch', function(event) {
console.log(event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});

Now, Let’s refresh our page and even after going “offline” you can still see the page content including an image.

An example at — https://skynet86.github.io/service-worker-example/sw-index.html

https://skynet86.github.io/service-worker-example/sw-index.html

Yes, you have done your first offline available page development.

Service worker does provide some other key features like,

  • Background Sync
  • Push notification

Which we will cover in another article.

Thank you for Reading. Happy Coding.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store