Skip to main content

HTML Web Workers

The Web Workers are the separate JavaScript code which runs in the background of the web page without affecting the user Interface.

What is Web Worker?

Everyone wants a website or application which work fast and can execute multiple operations simultaneously without affecting the performance of the page. However, sometimes we experience some delay response or degraded performance of page while executing some large operations. So this problem can be solved using the Web Workers.

Web Workers are the multithreaded object which can execute multiple JavaScript in parallel without affecting the performance of the application or webpage.

Following are some key features of the Web Workers:

  • Web-workers are threaded JavaScript.
  • Web-workers are the kernel-level thread.
  • Web-workers requires more space and CPU time.
  • Web-workers enhances the speed of a website.
  • Web-worker executes codes on the client side (not server-side).
  • Web worker threads communicate with each other using postMessage() callback method
note

Before working with HTML Web Workers you must have knowledge of JavaScript as the Web Worker depends on JavaScript.

Types of Web Workers:

In HTML5 Web Workers are of two types:

  • Dedicated Web Workers:

The dedicated worker can be accessed by only one script which has called it. The dedicated worker thread end as its parent thread ends. Dedicated workers are only used by one or single main thread.

  • Shared Web Workers:

It can be shared by multiple scripts and can communicate using the port. Shared workers can be accessed by different windows, iframes or workers.

Web Workers Browser Support:

Before learning the web Workers first, we need to check about the browser support. So following is the code which checks whether your browser is supporting or not.

if (typeof(Worker) !== "undefined") {  
// Yes! Web worker support!
// _Some code....._
} else {
// Sorry! No Web Worker support..
}

Create a Web worker file:

To create a Web Worker file we need to create an external JavaScript file.

Here we have created a web worker file for calculating the square of the number. And saved it with the name "worker.js".

Below is the code for worker.js file.

var i = 0;  

function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}

timedCount();

The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page.

note

Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.

Create a Web Worker Object

Now that we have the web worker file, we need to call it from an HTML page.

The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in "workers.js":

if (typeof(w) == "undefined") {  
w = new Worker("demo_workers.js");
}

Then we can send and receive messages from the web worker.

Add an "onmessage" event listener to the web worker.

w.onmessage  =  function(event){  
document.getElementById("result").innerHTML = event.data;
};

When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.

Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated.

To terminate a web worker, and free browser/computer resources, use the terminate() method:

w.terminate();

Reuse the Web Worker

If you set the worker variable to undefined, after it has been terminated, you can reuse the code:

w = undefined;

Full Web Worker Example Code

We have already seen the Worker code in the .js file. Below is the code for the HTML page:

<!DOCTYPE html>  
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>

<script>
var w;

function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
w.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
}
}

function stopWorker() {
w.terminate();
w = undefined;
}
</script>

</body>
</html>

Web Workers and the DOM

Since web workers are in external files, they do not have access to the following JavaScript objects:

  • The window object
  • The document object
  • The parent object