Sunday, July 02, 2017

javascript Web Worker

HTML Standard @whatwg
To send data to a worker, use the postMessage() method. Structured data can be sent over this communication channel. To send ArrayBuffer objects efficiently (by transferring them rather than cloning them), list them in an array in the second argument.

Web Workers @

HTML5 Web Workers @w3schools
"A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background."

"Web Workers is a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. In addition, they can perform I/O using XMLHttpRequest"

var worker = new Worker('doWork.js');

worker.addEventListener('message', function(e) {
  console.log('Worker said: ',;
}, false);

worker.postMessage('Hello World'); // Send data to our worker.
doWork.js (the worker):
self.addEventListener('message', function(e) {
}, false);
For security reasons web worker script can not be accessed from local filesystem, it must come from a server. There is a workarround by loading script from a blob string. That works in Chrome in Firefox, but not in Edge and IE.

var blob = new Blob(["self.onmessage = function(event) { 
postMessage(; }"], {type: 'application/javascript'});  
var worker = new Worker(URL.createObjectURL(blob));  
worker.onmessage = function(event) {  
  console.log(; //echo-worker
worker.postMessage("hello"); // send a message to the worker  

video HTML5 Web Workers by Jeff Prosise @Wintellect

Web workers run on a background thread, but threads may be reused by web browsers for multiple web workers. There are 2 types of workers:
  • Dedicated workers: can communicate only with the thread that created it
  • Shared workers: can share messages with multiple threads (less supported)
Workers are running in security restricted environment. It does not have access to DOM. All communication is with messaging, by value (no reference).

Shifting JavaScript into High Gear with Web Workers | Pluralsight
by Mike Van Sickle

No comments: