Web Workers allow you to run JavaScript in background threads.
There are two types of Web Workers: Dedicated Workers and Shared Workers. This article will focus on Dedicated Workers as they are more common and well supported.
A dedicated worker runs in it's own thread and communicates with other threads by passing "messages". This is useful as it allows scripts to run and not block the UI thread.
Below is a simple example of how you set up a worker.
if (!!window.Worker) {
// Set up the worker
// The code for the Worker has to be in a separate file.
var worker = new Worker('worker.js');
// A handler set up to receive messages from the worker
worker.onmessage = function (e) {
console.log(e.data);
}
// Handle worker errors
worker.onerror = function (e) {
var msg = e.message + ' (' + e.filename + ':' + e.lineno + ')';
console.log('Worker Error: ' + msg);
};
// Send a message (object, string or number etc)
worker.postMessage({ 'msg': 'Hello World!' });
}
want to know what the !! is for?
Messages are sent from thread to thread by using the postMessage
method. The data passed as an argument is copied. i.e. If you pass an object, the other thread will receive a copy, not a reference.
You can't access the DOM from a Web Worker but you can access things like WebSockets or Local Storage.
Below is some simple code in the Worker to receive messages.
onmessage = function (e) {
// Modify the message and post it back
postMessage(e.data.msg + " (Message Processed)");
}
Worker threads may also spawn their own workers (sub-workers).
From within the main thread:
worker.terminate();
From within the Worker:
close();
More reading:
Hello, my name is Lee and I work as a full-stack web developer specialising in Microsoft ASP.NET technologies. I love using Umbraco and also MANAGED, my own application management software.
Contact me at lee.gunn@secretorange.co.uk
Get in touch to talk about your project or just ask me a question.