Chrome, HTML5, webdev

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

Shared Worker Example

Web Workers - The bookA 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.
Btw, if you missed Part1 and/or Part2 of this series, you might want to read them first.
Shared web workers are identified in 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.

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