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.
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 @ W3.org
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."
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); //echo-worker
};
worker.postMessage("hello"); // send a message to the worker
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
Shifting JavaScript into High Gear with Web Workers | Pluralsight
by Mike Van Sickle
No comments:
Post a Comment