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.
"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: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
doWork.js (the worker):
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, 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(event.data); }"], {type: 'application/javascript'});
var worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = function(event) {
console.log(event.data);
};
worker.postMessage("hello");
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)