HTML 5 Web Workers In Action

Introduction

HTML5 introduced the web worker concept a long time ago. In this article, we will see the use of web worker in real scenarios.

In a nutshell, web worker is a JavaScript code that runs in the background (without refreshing the page) and without adding any performance overhead on the page. So that means, you can continue using your site by clicking here and there while web worker is doing its assigned functionality in the background.

Web worker runs independently of other scripts, so plumbing of code is relatively easy. It does support most of the common browsers today; i.e.,  Google Chrome, Internet Explorer (10 onwards), Firefox, etc.

Is Web Worker Supported for my development work?

Before we really go into developing the web worker, let us do a small check to see if it is supported in our development scenarios.

The below simple code should help you.

  1. if (typeof(Worker) !== "undefined") {  
  2.     alert(“Yes, Web worker is supported”);  
  3. else {  
  4.     alert(“No, Web worker is not supported”);  
  5. }  

After running the above script, if the answer is "Yes" … We are good to go ahead with web worker.

Basic syntaxes to get started

Create Web Worker Object,

  1. var worker = new Worker(“worker.js”);  

 

Send messages using web worker

To send the message from web worker, we need to add “onmessage” event listener to our worker role.

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

Terminate Web Worker

Once we are finished with the role of web worker, we should release the browser resources

  1. w.terminate();  

 

Reuse Web Worker

We can reuse the same web worker to carry out different dynamic functionalities.

  1. w = undefined;  

 

Once we set our web worker variable to undefined, we can reuse it for different purpose.

Web Worker Implementation Scenarios

I have seen others developing the Web workers effectively using the below implementation approaches:

  1. Web Worker File
  2. Inline code

We can pass complex types in/out of Workers such as File, Blob, ArrayBuffer, and JSON objects.

Web Worker File

As we discussed earlier, Web worker runs independently of other scripts. We can create an independent js file that will be designated to work as worker.

Let’s take a simple example of timer.

  1. Create a JS file named, timer.js
  2. Inside file, add below code which ticks the time by incrementing the count by 1.
    1. var time = 0;  
    2.   
    3. function timer() {  
    4.     time = time + 1;  
    5.     postMessage(i);  
    6.     setTimeout("timer()", 100);  
    7. }  
    8. timer();  
  1. In our page, use the above timer.js to perform web worker
    1. if (typeof(Worker) == "undefined") {  
    2.     var w = new Worker("timer.js");  
    3. }  

Inline code

We can also have the inline code for web worker processing.

  1. Instead of file, create a function for web worker.
    1. function webRoleFunction() {  
    2.     setInterval(function() {  
    3.         time = time + 1;  
    4.         postMessage(i);  
    5.     }, 100);  
    6. }  
  1. Now, we will have to convert above function to string equivalent
    1. var code = webRoleFunction.toString();  
    2. code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}"));  
  1. We will create a BLOB to store this code
    1. var blob = new Blob([code], { type: "application/javascript" });  
    2. var blobURL = window.URL.createObjectURL(blob);  
    3. var w = new Worker(blobURL);  

Blob URLs are unique and last for the lifetime of your application. We should explicitly release the created BLOBs by

  1. window.URL.revokeObjectURL(blobURL);  

 

Loading External Scripts

Web worker runs in its own thread. That means, you will have to load the external scripts by providing the absolute urls only. Note, relative urls will not work to load external files.

importScripts() function can be used to load external files.

  1. w.onmessage = function (e) {  
  2. var data = e.data;  
  3.   
  4.   if (data.url) {  
  5. var url = data.url.href;  
  6. var index = url.indexOf('index.html');  
  7. if (index != -1){  
  8. url = url.substring(0, index);  
  9. }  
  10. importScripts(url + 'externalScript.js');  
  11.  }  
  12. }  

Error Handling

We should have a JavaScript logic to handle the errors raised by web worker.

  1. var worker = new Worker('workerWithError.js');  
  2. worker.addEventListener('message', onMsg, false);  
  3. worker.addEventListener('error', onError, false);  
  4. worker.postMessage(); // Start worker without a message

Up Next
    Ebook Download
    View all
    Learn
    View all