HTML5 Web Workers Example
Web Workers are a welcome addition to the HTML. Since JavaScript is not a multiple threaded environment, it becomes impossible to run multiple scripts at the same time. Also when running scripts in html, the web page becomes unresponsive until the script stops or has run its course(this affects performance and leads to a bad user experience).
Web workers allows web pages or browsers run scripts in the background. It’s always better to run CPU intensive scripts in the background to avoid distorting the user experience and causing the webpage to become unresponsive.
In this example we are going to learn about HTML5 Web Workers and how to use them. For this example we will use:
- A computer with a modern browser installed
- notepad++
1. Getting Started
Since Web workers run JavaScript in the background, web page performance and user experience is not distorted or affected. To create a new worker you simply
var worker= new Worker("worker.js");// creating a new worker.
We simply instantiate the Worker()
object and passing the URI of the JS file to run as an argument. Before spawning a worker to run JS code, it is sensible to check if the browser supports it(for backward compatibility). You can do this by wrapping your code in an if
statement.
if (typeof(Worker) !=="undefined") {// web workers are supported in this browser var worker= new Worker("worker.js");// creating a new worker. } else {//web worker not supported alert("Your browser does not support web workers, please download the latest version"); }
If the browser supports web workers, we easily create a web worker object, with the URI of the required JS file as an argument. If the JS file supplied as an argument does not exist, the process or worker fails silently.
Note: Web workers do not have access to the following JavaScript objects:
- The window object
- The document object
1.1 Sending messages to and from a worker
In this section we will learn how to send messages to our worker and receive messages from our worker. To send message to the worker we simply call
worker.postMessage()
Depending on browser vendor or version, you can pass a string, JSON or an array as an argument to the postMessage
if (typeof(Worker) !=="undefined") {// web workers are supported in this browser var worker= new Worker("worker.js");// creating a new worker. worker.postMessage("processs this");//post a message to the worker } else {//web worker not supported alert("Your browser does not support web workers, please download the latest version"); }
Inside the worker we can process information or message received by registering an event handler.
onmessage = function(e) { console.log('Message has been received and it is been processed'); //log the message to console var workerResult = e.data; console.log('returning message back to main script'); postMessage(workerResult); }
We can send messages from our worker by calling postMessage()
and passing the data we want to send as an argument. To receive messages sent by our worker we simply use:
worker.onmessage=function(e){ //the data sent by the worker can be accessed is available in the event data attribute }
Lets create a full example to describe what we have learnt so far.
index.html
<!DOCTYPE html> <html lang=en> <head> <style> html, body{ width:100%; height:100%; margin:0%; font-family:"helvetica","verdana","calibri", "san serif"; overflow:hidden; padding:0%; border:0%; } </style> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/> <title>HTML5 WEB WORKER EXAMPLE</title> </head> <body onload=init()> <script> if (typeof(Worker) !=="undefined") {// web workers are supported in this browser var worker= new Worker("index.js");// creating a new worker. } else {//web worker not supported //alert the error alert("Your browser does not support web workers, please download the latest version"); } //function called to initialize some global variables function init(){ //store a reference to the textbox b= document.getElementById("press"); // add a click listener to the button b.addEventListener("click",clicked); c= document.getElementById("text"); } //function clicked when the button is clicked function clicked(){ //send a message to the worker js worker.postMessage(c.value); } //here we listen for the worker message worker.onmessage = function(e) { console.log('Message received from worker:'+ e.data);// we log the data alert(e.data);// we also show a dialog with the data } </script> <input type=text id=text ><br> <input type=button id=press value=press> </body> </html>
index.js
//this worker simple sends back any message posted to it, note that workers are actually used for CPU intensive tasks not trivial tasks like this onmessage = function(e) { console.log('Message has been received and it is been processed'); //log the message to console var workerResult = e.data; console.log('returning message back to main script'); postMessage(workerResult); }
The worker simply returns the message posted to it from the main thread. Fill in any value in the textbox and click the button below, the data in the textbox is posted to the worker for processing.
1.2 Terminating Workers
You can terminate a worker by calling
worker.terminate();//where worker is a Worker object.
2. Summary
In this example we learnt about web workers, how to create and use them.
3. Download the source code
Download
You can download the full source code of this example here: html5webworkerexample