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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 859
    Comment on it

    Introduction

    • 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>
    
    <script>
    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 = event.data;
     };
     } 
    else 
    {
     document.getElementById("count").innerHTML = "There is no web worker.";
     }
    }
    function stopWorker1() 
    {
     worker.terminate();
     worker = undefined;
    }
    </script>
    

    workers1.js

    addEventListener("message", function (event) {
        var date1 = new Date();
        var currentDate1 = null;
        do {
            currentDate1 = new Date();
        } while (currentDate1 - date1 &lt; event.data);
        postMessage(currentDate1);
    }, 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");

    pagescript.js:

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

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

    thread1.js:

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

    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.

    pagescript.js:

    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.

    thread1.js:

    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){ 
    alert(event.data);
    
    }
    sharedWorker1.port.postMessage('Hello');
    

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

    Prime.js:

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

    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.

    References


    http://code.tutsplus.com/tutorials/getting-started-with-web-workers--net-27667

    http://www.codeproject.com/Articles/168604/Combining-jQuery-Deferred-with-the-HTML-Web-Worke

    https://html.spec.whatwg.org/multipage/workers.html#shared-workers

    http://www.storminthecastle.com/2013/04/19/make-your-ui-more-responsive-with-html5-web-workers/

    http://mobilejquery.wordpress.com/2013/05/20/ajax-call-with-web-worker/

    http://www.developer.com/lang/jscript/7-things-you-need-to-know-about-web-workers.html

    http://techslides.com/html5-web-workers-for-ajax-requests/

    http://www.w3schools.com/html/html5_webworkers.asp

    http://tutorials.jenkov.com/html5/web-workers.html

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
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: