JavaScript is single-threaded
if ( window.Worker ) {
// happiness! we got Web Workers
} else {
// sad puppy
}
var worker = new Worker( '/js/task.js' );
<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/
importScripts( 'script1.js', 'script2.js' );
self
and this
refer to the global scope.// 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 */);
worker.postMessage(); // Start the worker.
/* ... */
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 );
// worker power down
self.close();
// terminate worker from main thread
worker.terminate();
Chrome
worker.postMessage( ArrayBuffer, [ ArrayBuffer ] );
// 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' );
}
};
"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>