HTML5 APIs – Web Workers


What is Web Worker?

HTML5 introduced Web Workers which is designed to run Javascript code in the background without affecting the performance of the webpage.

Web Workers is a JavaScript code which runs in the background of the web page without affecting the user Interface.

Web Workers are the multithreaded object which can execute multiple JavaScript codes in parallel inside the webpage.

We can do any operations in webpage like clicking, submitting etc, while the web worker Javascript code only runs in the background.

But until the Javascripts are executed, the web page remains unresponsive.

Why Web Workers are used ?

Everybody may experience some delay response from our webpage while doing multiple operations simultaneously.

Web Worker solved all these problems since it runs in background, allows thee webpage works fast and execute multiple operations simultaneously without affecting the performance of the page.

What are the key features of the Web Workers ?

Some of the key features of Web Workers are listed below,

1. Web Workers are multi-threaded JavaScript code.

2. Web Workers are the kernel-level thread.

3. Web Workers requires more space and CPU time.

4. Web Workers boosts the webpage speed.


5. Web Worker executes codes on the client side environment (not server-side).

6. Web Worker threads communicate with each other using postMessage() callback method

Tutorial on html !!!

Click to Learn More about – HTML Tutorial for beginners

What are the drawbacks of Web Workers ?

Web workers are external javascript files so they don’t have access for the JavaScript objects.

1. Window objects

2. Document objects

3. Parent objects.

What are the types of Web Workers ?

There are two types of Web Worker

1. Dedicated Web Workers

2. Shared Web Workers

1. Dedicated Web Workers

Dedicated Web Workers can be accessed by only one script which has called it (parent thread).

When the parent thread ends, the dedicated worker thread will also end.

Dedicated Web Workers threads are used which have only one main(parent) thread.

For example, if we want to add A and B, this parent thread allows to enter two numbers and its sent to dedicated Web Worker then added and the particular result is displayed as output.

There the parent thread ends, thereby ending Dedicated Web Workers thread.

2. Shared Web Workers

Shared Web Workers is accessible by multiple scripts and communicates each other using ports.

These multiple scripts communicates each other even in different windows, iframes or workers.

So Shared workers can be access data across different windows, iframes or workers.

If the Shared Web Workers accessed from different browsers, then all those browsing contexts must share the exact same origin (same protocol, host, and port).

For example, if we want to add two numbers and also we want to multiple two numbers A and B.

Addition and Multiplication functions are handled by two different script files.

Both scripts are accessed by Shared Web Workers to get both different results and displayed in the webpage as output.

Note : Shared Web Workers cannot be shared between documents loaded in private and non-private windows in Firefox(bug 1177621).

1. Checking Web Workers Browser Support

We have to check the browser support before implementing the Web Workers,

Example :

<!DOCTYPE html>
<html>
<head>
  <title>Checking Browser Web Worker API</title>
  <script type="text/javascript">
   function checkBrowserWebWorker()
   {
    if(typeof(Worker)!=="undefined"){
	    document.getElementById("supported").innerHTML="<br/>This browser supports Web Workers.";
      }
     else
      {
	      document.getElementById("unsupported").innerHTML="<br/>This browser don't support Web Workers.";}
   }
</script>
</head>
<body>
<h2>Checking Browser Web Worker API</h2>
<button onclick="checkBrowserWebWorker();">Check Browser Support</button>
<div id="supported"></div>
<div id="unsupported"></div>
</body>
</html>

2. Create a Web Worker File

Web Worker File is just a simple external javascript file.

This Javascript file method is a postMessage() method used to post a message back to the HTML page.

Example :

var i = 0;

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

timedCount();

3. Create a Web Worker Object

We have already created the Web Worker sample javascript file.

Now we have to call it from inside our webpage.

Example :

<!DOCTYPE html>
<html>
<body>

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

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

</script>

</body>
</html>

Above code checks if the worker already present or not.

if not, then it creates a new web worker object and runs the code in “web_workers.js”.

4. Send and Receive messages

Once the Web Worker Object is created, then we can send and receive messages from the web worker.

“onmessage” event listener should be added in the script.

Whenever 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”.

Example :


<!DOCTYPE html>
<html>
<body>

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

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

</script>

</body>
</html>

5. Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages even after the script is executed completely.

To stop this listening we have to terminate the web worker by calling terminate() method.

Example :

<!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("web_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();
}

</script>

</body>
</html>

Output :

Tutorial on html !!!

Click to Learn More about – HTML Tutorial for beginners

6. Reuse the Web Worker

Web Worker can be reused for further purpose, we have to first terminate the Web Worker by calling terminate() method.

The we can reuse it by setting the variable as “undefined”.

Example :

<!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("web_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>

2 comments

  1. Heya! I understand this is sort of off-topic but I needed to ask.

    Does managing a well-established website such as yours require a lot of work?
    I’m completely new to operating a blog but I do write in my diary every day.
    I’d like to start a blog so I can easily share my own experience and feelings online.
    Please let me know if you have any recommendations
    or tips for brand new aspiring blog owners. Thankyou!

    1. Hi Initially i tried google blogger and lot of features are not available in that also alignment text issues are there then i moved to WordPress, This is really good and easy to handle, lot of plugins are available also we can customise the themes and it really helps us post our thoughts easily, So i suggest you to go through WordPress installation guide also select the good theme for your website that is the most important thing. Keep rocking keep faith and keep working Thank you.

Comments are closed.