Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Web Worker

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 838
    Comment on it


    • A web worker in html5 is a simple JavaScript file.
    • Html5 have an extended functionality to create thread that continues to work on there own in the background without making any compromise in the performance speed of the of the page.
    • Clicking, selecting items, etc..,web workers run without causing any processing halt.
    • A separate '.js' file is used to code for web workers.
    • The code runs in separate place and it has no access to window object and to DOM so communication is done via messages.
    • The messages are serialized and de-serialized, that's why input and output is always copied meaning we cant pass any object references into Workers.

    Why it is used

    • In JavaScript,sometimes you might have faced such dialog boxes with some message like There is some script running in the background,is taking much time in execution. Do you want to continue or not.
    • Secondly, DOM manipulation as it is a costliest operation that you can do with JavaScript. As a result your script becomes a good source for refactoring.
    • And the Never-ending Loops.

    What is a Web Worker?

    • A web worker is defined as a single JavaScript file i.e. loaded and executed in the background without causing any delay on the performance.
    • They are of two types:
      Dedicated workers: these are linked to their particular creator (i.e. the script in which the worker is created).
      Shared workers:these are not linked to any particular creator, any script within the same domain can communicate with them through port number.

    For implementation,the specific code which is written in a separate new .js file, needs to confirm to a specific "interface":

    • onmessage: this function is used to receive messages from web worker.
    • onconnect: this function is used in shared worker where it receives notification from different UI threads present within the same domain.
    • postMessage: this function is used to send message back to the calling script or page. As we know a Worker doesnt have any access to the window object or DOM still we can use some functions like: setTimeout setInterval XMLHttpRequest

    For Example:

    Total count: <output id="count"></output>
    <button onclick="startWorker1()">Start Worker1</button>
    <button onclick="stopWorker1()">Stop Worker1</button>
    var worker;
    function startWorker1()
     if(typeof(Worker) !== "undefined") 
     if(typeof(worker) == "undefined")
     worker = new Worker("workers1.js");
     worker.onmessage = function(event) 
     document.getElementById("count").innerHTML =;
     document.getElementById("count").innerHTML = "There is no web worker.";
    function stopWorker1() 
     worker = undefined;


    addEventListener("message", function (event) {
        var date1 = new Date();
        var currentDate1 = null;
        do {
            currentDate1 = new Date();
        } while (currentDate1 - date1 &lt;;
    }, false);

    Creating a Dedicated Web Worker - These are linked to their particular creator. - Web worker do not have access to the DOM or windows object,therefore communication is done through an event interface only. - The calling script passes data as a parameter in postMessage() method and receives the result through an onmessage event handler present in it. var worker = new Worker("thread1.js");


    var worker1 = new Worker("thread1.js");
    // receive messages from web worker
    worker1.onmessage = function(event) {
            alert(event .data);
    // send message to web worker

    The web worker script receives and sends data through "onmessage() event handler and postMessage()method accordingly:


    self.onmessage = function(event) {
    self.postMessage("Hello " +;

    The message data can be a string, number, boolean, array, object, null or undefined. Data is always passed by value and not by using object. Data is serialized then de-serialized during the communication process.

    Debugging Workers and Error Handing

    • In Chrome Developer Tool, one can debug the worker code as like any other JavaScript code.
    • Web worker code may have errors and i.e. logic errors only, which are due to the data passed by the page script.
    • Web worker have error event handler to catch errors.
    • The handler event consist of properties: filename: the name of the script which caused the error; lineno: the line number where the error occurred; and message: the description of the error.


    worker1.onerror = function(event) {
            alert("Error in file: "+event .filename+"&amp;line: "+event .lineno+"&amp;Description: "+   event .message);

    Loading Further JavaScript Files In a web worker we can add one or more JavaScript libraries as needed,using importScripts(), e.g.

    importScripts("library1.js", "library2.js", "library3.js");

    Stopping a Dedicated Web Worker "close()" method is used to stop the web worker thread execution, e.g.


    self.onmessage = function(event) {
            if (event .data == "STOP!") self.close();

    Creating a Shared Web Worker - Shared workers, can be shared among all the pages from an origin or you can say from the same domain. - For creating a shared worker, the Url of the calling script or the worker's name is pass as an argument within the SharedWorker constructor. - The main difference between dedicated workers and shared workers is that in shared worker port number is also attached to keep track of the parent scripts accessing them.

    var sharedWorker1 = new SharedWorker('Prime.js');
    sharedWorker1.port.onmessage = function(event){ 

    shared worker have onconnect event to listen when a new client want to connect to it.


    onconnect = function(event) {
    var clientPort = event.source;
    clientPort.onmessage = function(event) {
    // contains the message send by client
    var data =;

    The main advantage of their shared behaviour is that, you can maintain the same state in different tabs of the same application.

    Restrictions - Firstly web workers have no access to the DOM; they cannot even read or modify the HTML document. - Secondly, they cannot access global variables or JavaScript functions within the page. - Moreover,there access to some objects is restricted, for e.g. window.location properties are read-only. - They cannot be used in large numbers because of their performance and memory cost.

    Web Worker Browser Support - The cross-browser support is fairly good for dedicated workers with current versions of Chrome, Safari, and Firefox. - Even IE10 supports it. - However, shared workers are only supported on current versions of Chrome and Safari. - Apple also included web worker support starting with iOS 5.0.


 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: