Web Workers : Introduction

Sujeet Kumar Jaiswal
Sujeet’s Blog
Published in
3 min readApr 2, 2016

A web worker is a JavaScript that runs background in a separate thread and live in a self-contained execution environment, which enables to process heavy computations without blocking the main UI thread.

Web Workers are a mechanism by which a script operation can be made to run in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.
-MDN

Use of web-worker for process extensive task

Check Web Worker Support

Method 1:

if(!!window.Worker){
//Worker is supported
}else{
//Worker is not supported
}

Method 2:

if(typeof(Worker) !== “undefined”) {
// Web worker support!
} else {
// Sorry! No Web Worker support..
}

Worker is a constructor function defined in the global scope (window), if the browser supports it. And this is used to detect the feature.

How to use worker ?

To create a new worker, just use the Worker() constructor, passing the URL that specifies the worker to run:

var worker = new Worker('worker_utils/worker_1.js')

Note: if the URL passed is relative, it will resolved relative to the URL of the document that contains the script that called the worker and if the URL specified is absolute, it must be of the same origin.

Once you have the worker object, you can send data to worker using the postMessage().

var data_to_send = "any type of data"; // String | JSON | anything
worker.postMessage(data_to_send);

Note: The value you pass in postMessage() will be cloned.

To receive message from the worker, you have to listen for message event of the Worker object(worker):

worker.onmessage = function(event){
var message = event.data;
console.log(message);
}

If the Worker Object throws an exception which is not handled in intself, the exception will propagate as an event that you can listen for:

worker.onerror = function(event){
console.log("Error at " + event.filename + ":" + event.lineno + ":" + event.message );
}

Note : The error event have three details about the error : filename,lineno and the error message, which can be used for debugging our worker.

Note: Worker object define the standard addEventListener() and removeEventListener() methods, that can be used in place of onmessage and onerror.

What’s inside the worker ?

Worker contains mainly two things :

  • Code that listens to message to start the execution
  • Code to be executed and sending the response back to the main thead.
function messageHandler(event){
var received_data = event.data;
var data_to_send_back;
//Do something with the data
postMessage(data_to_send_back);
}
addEventListener('message',messageHandler,true);

Remember the following when writing code inside the worker

self refers to global object but its not window object. The context is represented by DedicatedWorkerGlobalScope if the worker is dedicated or SharedWorkerGlobalScope if the worker is of shared type.

  • Both DedicatedWorkerGlobalScope and SharedWorkerGlobalScope inherits from WorkerGlobalScope which has all the core properties of JavaScript global object like JSON object, isNaN function, Date() Constructor etc.
  • does not have access to DOM
  • location data are available but only in read only
  • Geo-location data are not available. The navigator object is present but have data limited to appName, appVersion, platform, userAgent and onLine
  • You have access to XMLHttpRequest, LocalStorage, IndexedDB, WebSockets.
  • You also have access to timer methods like setTimeout(), clearTimeout(), setInterval() and clearInterval().

Importing Scripts in Web workers

importScript() is a global function that helps web workers to import scripts in the same domain into there scopes.

importScripts();                    /* imports nothing */
importScripts('foo.js'); /* imports just "foo.js" */
importScripts('foo.js', 'bar.js'); /* imports two scripts */

How to stop web worker once started ?

  1. terminate() : Used when web worker needs to be immediately killed from the UI thread without completing its on-going execution.
  2. close(): Used to kill the web worker thread from inside the worker thread.
//Terminate() :: From the UI Thread
worker.terminate()
//Close() :: From inside the worker itself
close()

Types of Workers

  • Dedicated web workers : a dedicated worker is only accessible by the script that called it. [All the above codes are for Dedicated web workers]
  • Shared web workers: A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers.

Few others are :

  • Service workers
  • Chrome workers
  • Audio workers

--

--