Web Workers

JavaScript ain't single threaded anymore

what's a web worker?



“This specification defines
an API for running scripts in the background  
 independently of any user interface scripts.”  


  “This allows for long-running scripts  
 that are not interrupted by scripts  
 that respond to clicks or other user interactions,  
 and allows long tasks to be executed without yielding  
 to keep the page responsive.
   


- W3C Specification  

Some more facts


  • Workers are HTML5
  • Uses MessgePort (postMessage) for communication
  • Browser support down to IE10 (single threaded polyfill available for <IE10)
  • Using real browser processes and are using all cores!
  • Workers can span sub-workers


 

example of web worker usage




 Blocking the windows single thread 

 http://embed.plnkr.co/Z2SdNw 



 Using a Web Worker 

  http://embed.plnkr.co/SOA4sp    

 BARRIERS / LIMITATIONS 


 Limited access to features 


navigator object

location object (read-only)

XMLHttpRquest

setTimeout() and co.

Application Cache

Importing external scripts using importScripts()

Spawning other Web Workers

 DON'T have access to 


DOM (it's not thread-safe)

window object

document object

parent object

Shared worker



  • Has a daemon nature and accepts connections
  • Multiple windows can connect to the same worker
  • Not supported by IE at all

Shared Worker master


 master.js 
var worker = new SharedWorker('jsworker.js');

worker.port.addEventListener('message', function(e) {
  alert(e.data);
});

worker.port.start();
worker.port.postMessage('Hi Slave!');

Shared worker slave


 slave.js 
self.addEventListener('connect', function (event) {
  var port = event.ports[0];
  port.addEventListener('message', function (e) {
    port.postMessage('Hi Master!');
  });
  port.start();
});

  Multithreading example  




  WIFI Password Cracking in the browser :-)  

   http://embed.plnkr.co/mnlQ6P    

using parallel.js


  • High level access to multicore processing using web workers
  • Accepts functions to execute (will create Blob and fallback to eval.js)
  • Chainable with promise syntax
  • Helper for executing multi-threaded core operations (map, reduce etc.)

var slowSquare = function (n) { 
  var i = 0; 
  while (++i < n * n) {}
  return i; 
};
 
// Create a job
var p = new Parallel(100000);
 
// Spawn our slow function
p.spawn(slowSquare).then(yourCallback);

Web Workers

By Gion Kunz

Web Workers

Small presentation about HTML5 web workers

  • 2,434