Web workers
Saturday, February 2nd, 2013 | Limited, Programming
These days, we’re all trying to do very clever things in the browser, that take up heaps of system resources. Often, your application will be doing so much that the system can barely cope – and with JavaScript being a single thread language, heavy processing can tie the UI up and make the user think the page has crashed.
Enter web workers – a background process that essentially allows you to do concurrent JavaScript. You can create a background process from a script, and then send messages back and forth between it and the page, ensuring you don’t tie up the UI.
They’re really simple to use too.
var worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {
console.log('Message from worker: ', e.data);
}, false);
worker.postMessage('Hello, World!');
Then create a simple JavaScript for your worker.
this.addEventListener('message', function(message) {
this.postMessage(message.data);
}, false);
You can read more about web workers on HTML5 Rocks.
These days, we’re all trying to do very clever things in the browser, that take up heaps of system resources. Often, your application will be doing so much that the system can barely cope – and with JavaScript being a single thread language, heavy processing can tie the UI up and make the user think the page has crashed.
Enter web workers – a background process that essentially allows you to do concurrent JavaScript. You can create a background process from a script, and then send messages back and forth between it and the page, ensuring you don’t tie up the UI.
They’re really simple to use too.
var worker = new Worker('worker.js'); worker.addEventListener('message', function(e) { console.log('Message from worker: ', e.data); }, false); worker.postMessage('Hello, World!');
Then create a simple JavaScript for your worker.
this.addEventListener('message', function(message) { this.postMessage(message.data); }, false);
You can read more about web workers on HTML5 Rocks.