Web Workers

the background threads of JavaScript



Balázs Suhajda


interface developer / founder @ onereason 
co-founder of Malmö Open Device Lab 


@suhajdab





I lived in sudan

First computers



ZX Spectrum emulator in JavaScript




WEB WORKERS











JavaScript is single-threaded

WebWorkers


  • work in a new thread
  • live in restricted, thread-safe environment
  • communicates via postMessage API
  • message / data is copied, not shared
  • no access to DOM

Available features








Workers' Performance

Support



Code




  • detecting support
  • setting up
  • communication with
  • debugging

Detection






if ( window.Worker ) { // happiness! we got Web Workers } else { // sad puppy }

Setting up - separate file





  var worker = new Worker( '/js/task.js' );

Setting up - inline


  <script id="worker-src" type="javascript/worker">     // avoiding script execution by unknown type attribute     function task () {} </script>
<script> var textContent = document.getElementById('worker-src').textContent, blob = new Blob([textContent]), blobURL = window.URL.createObjectURL(blob), worker = new Worker(blobURL); </script>

blob:http%3A//example.com/2c8a577c-eec3-4b19-8165-bad8939b8e7d
chrome://blob-internals/

Additional scripts





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

Scope






In context of a worker, 
both self and this refer to the global scope.

Communication


 // main script worker.addEventListener( 'message', function ( event ) {   // event.data = payload
   // event.target = reference to worker }, false ); worker.postMessage( /* payload */);

 // worker script self.addEventListener( 'message', function ( event ) {
   // event.data = payload
   // event.target = DedicatedWorkerGlobalScope
 }, false );
 self.postMessage( /* payload */);

Starting






 worker.postMessage(); // Start the worker.
codepen

error handling


 /* ... */

 function onError( e ) {
     // e.filename - the name of the worker script that caused the error
     // e.lineno - the line number where the error occurred
     // e.message - a meaningful description of the error
 }

  

 var worker = new Worker( '/js/task.js' );
 worker.addEventListener( 'error', onError, false );

Terminating



 // worker power down self.close();


 // terminate worker from main thread worker.terminate();

Debugging






No console.log!!
:O


Chrome


IE (11)



Firefox




????


Transferable Objects

 worker.postMessage( ArrayBuffer, [ ArrayBuffer ] );


http://html5-demos.appspot.com






Got time?





Shared workers







Support








Shared Workers are associated with a port 
to keep track of the parent script accessing them

Communication

 // main script var sharedWorker = new SharedWorker( '/js/shared-worker.js' );
sharedWorker.port.addEventListener( 'message', onMessage, false ); sharedWorker.port.start(); sharedWorker.port.postMessage( 'ping' );

 // shared worker script
 self.onconnect = function( event ) {
    // event.source contains the reference to the client's port
    var clientPort = event.source;
    // listen for any messages send by this client
    clientPort.onmessage = function( event ) {
        // event.data contains the message send by client
        var data = event.data;
        // Post Data after processing
        clientPort.postMessage( 'processed data' );
    }
 };

Real world




CPU core estimator


http://wg.oftn.org/projects/core-estimator/demo/

Uses cases



text parsing

big data

image processing

games




"If you’re doing any computation with JavaScript you should definitely opt to use Web Workers if they’re available – the result is both faster and a better experience for the end user."

Computing with JavaScript Web Workers - John Resig   2009






1r.nu/workers


</presentation>

Made with Slides.com