Chrome, HTML5, webdev

Web Workers (Part 3 Out Of 3) – Shared Wrokers

Shared Worker Example

A web worker is a single JavaScript file loaded and executed on a separate thread (=background and not the UI thread). Dedicated web workers are linked to their owner/creator which is the script that called and loaded them. Shared web workers allow any number of scripts to communicate with a single worker. They are identified in one of two ways: either by the URL of the script used to create it, or by explicit name. In the code below we will see how it can be done.

 

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Shared Web Workers: Show And Tale</title>
  </head>
  <body>

    <h1>Shared Web Workers: Show And Tale</h1>
    <article>
      To create a shared web worker, you pass a JavaScript file name to a new instance of the SharedWorker object:
      <br/>var worker = new SharedWorker("jsworker.js");
      <br/>
      <output id="result"></output>
    </article>
    <script>
      var worker = new SharedWorker('sharedWorker1.js');
      worker.port.addEventListener("message", function(e) {  
        document.getElementById('result').textContent += " | " + e.data;  
      }, false);  
      worker.port.start();  
      // post a message to the shared web worker  
      console.log("Calling the worker from script 1");
      worker.port.postMessage("script-1");

    </script>

    <script>
      console.log("Calling the worker from script 2");
      worker.port.postMessage("script-2");
    </script>
  </body>
</html>

// This is the code for: 'sharedWorker1.js' file
// Shared workers that handle the connections and Welcome each new script
// 
var connections = 0; // count active connections  
self.addEventListener("connect", function (e) {  
    var port = e.ports[0];  
    connections++;  
    port.addEventListener("message", function (e) {  
        port.postMessage("Welcome to " + e.data +
 		" (On port #" + connections + ")");  
    }, false);  
    port.start();  
}, false);

 

Shared web workers can:

  • load further scripts with importScripts()
  • attach error handlers, and
  • run the port.close() method to prevent further communication on a specific port.

Features Available to Workers

Due to their multi-threaded behavior, web workers only has access to a subset of JavaScript’s features:

  • The navigator object
  • The location object (read-only)
  • XMLHttpRequest
  • setTimeout()/clearTimeout() and setInterval()/clearInterval()
  • The Application Cache
  • Importing external scripts using the importScripts() method
  • Spawning other web workers

Workers do NOT have access to

  • The DOM (it’s not thread-safe)
  • The window object
  • The document object
  • The parent object

Loading External Scripts

You can load external script files or libraries into a worker with the importScripts() function. The method takes zero or more strings representing the filenames for the resources to import. This example loads script1.js and script2.js into the worker: worker.js:

importScripts('script1.js');
importScripts('script2.js');

Which can also be written as a single import statement:

importScripts('script1.js', 'script2.js');

you might want to debug your worker with this pattern

 

var worker = new Worker("worker.js");
worker.onerror = function(e){
  throw new Error(e.message + " (" + e.filename + ":" + e.lineno + ")");
};

and if you are on Chrome (17+) check this great option under the dev tools:

In case you missed Part1 and/or Part2 of this series – feel free to check them out.

More Sources

Standard