A guided tour on

Web Workers


by @igorsoarez





So what are Web Workers?

API

Defined by

  • World-Wide Web Consortium (W3C)
  • Web Hypertext Application Technology Working Group (WHATWG)


Used to perform a computationally expensive task without interrupting the user interface



How?


<script>
  var worker = new Worker('worker.js');
</script>

Browser ignores MIME type


Workers play by special rules

  • Separate parallel execution environment
  • Distinct event loop
  • No access to DOM
  • No access to UI Events
  • No window, document, parent, console, alert
  • No shared state

No shared state ?!?!?!

<script>
  var worker = new Worker('worker.js');
  worker.onmessage = function (event) {
    console.dir(event.data);
    worker.postMessage({ letter: 'R', number: 42 })
  };
</script>
worker.js
self.postMessage({ name: 'Rulio' });
self.onmessage = function (event) {
  // do something with event.data;
};

No sharing - messages are copied


What CAN they do?

  • Use the navigator object
  • Use the location object (read-only)
  • XMLHttpRequest
  • setTimeout/setInterval/...
  • The Application Cache
  • importScripts()
  • create subworkers - new Worker('subworker.js')

Handling errors


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

Stoping a worker


From the origin:

worker.terminate()

From the worker:

self.close()

Why?

  • Computationally expensive tasks
  • Background I/O
    • Polling webservices
  • Coordinating multiple tabs
    • with Shared Workers

Shared workers

  • are named
  • any script running in the same origin can communicate by the URL or name
  • use port (MessagePort objects) to communicate
  • require worker.port.start()
  • have onconnect

Example

<script>
  var worker = new SharedWorker('sharedworker.js', 'name');
  worker.port.onmessage = function(e) { //not worker.onmessage!
    console.dir(e.data);
  };
</script>

sharedworker.js

onconnect = function(e) {
  var port = e.ports[0];
  port.postMessage('Hello World!');
};

need to use onconnect


Web Workers are heavyweight


Expected to be:

  • Long lived
  • High start-up performance cost
  • High per-instance memory cost


X

Thank you!