[HTML5] Web Worker


If you are an experienced developer, you know what the background processing is. Web Worker API defines how you can run JavaScript code in the background, independently of other scripts.

1. Web Worker

Web workers interact with the main script via messages. When you work with web workers, you need to always take care of 2 spots : main and worker.

The web worker code is always placed in a separate file and be called from the main script.

In the main script, a “Worker” object is created and running. You can use the “postMessage()” method to pass messages back and force. Also in the main script you can handle various events from the worker such as “onmessage“.


2. Detecting the Feature

The web worker’s main object is “window.Worker“. You can check whether the feature is available like the followings:

function support_webWorker1() { return "Worker" in window; }
function support_webWorker2() { return !!window.Worker; }

Web workers are supported by all major browsers. (IE10 or later).


3. Creating Worker Script

You need put the worker code in a separate file.

Suppose you need to do the very complex calculation.

self.addEventListener("message", function (event) {
  var result = performComplexCalculation(event.data);
}, false);

function performComplexCalculation(seed) {
  // very complex logic - bogus
  var k;
  for (var i = 0; i < 100000; i++)
    for (var j = 0; j < 10000; j++)
      k = 0;

  return parseInt(seed) + 100;

Workers are based on the message exchanges. Therefore you need to handle the “message” event in the worker script. The “event” object has a “data” property to access the data passed with a message.

When the worker has finished its job, you can pass the result back to the main script using the “postMessage()” method.


4. Creating the Worker Object

In the main script, the “Worker” object is created by passing the worker script file.

var worker = new Worker("../Scripts/MyWorker1.js");


5. Main Script

Here is the script code in the main file.

var worker;

function support_webWorker() {
  return !!window.Worker;

function calculate() {
  var seedData = $("#data").val();
  worker.postMessage(seedData); // start the worker
  document.getElementById("result").textContent = "Processing ...";

function stop() {
  document.getElementById("result").textContent = "Worker Stopped.";

$("document").ready(function () {

  if (!support_webWorker()) {
   alert("Web Worker is not supported.");
  } else {
    worker = new Worker("../Scripts/MyWorker1.js");
    worker.addEventListener("message", function (event) {
      document.getElementById("result").textContent = event.data;
    }, false);

Here is the body part of the html document.

  <input type="number" id="data" value="30" min="0" max="100" />
  <input type="button" id="calcBtn" value="Calculate" />
  <input type="button" id="stopBtn" value="Stop" />
  <br /><br />
  <div id="result"></div>

You can start the worker by sending messages to it. Look at the “calculate()” function.


6. Closing the Worker

You can close the worker in 2 ways.

In the main script, you can call the “terminate()” method.


In the worker script, you can call the “close()” method.



7. Events

In the main page, you can handle the following events:

  • onmessage : enables to receive worker messages in the main script
  • onerror : handles an error occurred in the worker

In the worker script, you can receive the message too.

  • onmessage : enables to receive worker messages from the main script

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s