A web worker is a simple way to run scripts in background threads as the worker thread can perform tasks (including I/O tasks using xmlHttpRequest) without interfering with the user interface. Once created, a worker can send messages which can be different data types (except functions) to the JavaScript code that created it by posting messages to an event handler specified by that code (and vice versa.)
Workers can be created in a few ways.
The most common is from a simple URL:
var webworker = new Worker("./path/to/webworker.js");
It's also possible to create a Worker dynamically from a string using URL.createObjectURL()
:
var workerData = "function someFunction() {}; console.log('More code');";
var blobURL = URL.createObjectURL(new Blob(["(" + workerData + ")"], { type: "text/javascript" }));
var webworker = new Worker(blobURL);
The same method can be combined with Function.toString()
to create a worker from an existing function:
var workerFn = function() {
console.log("I was run");
};
var blobURL = URL.createObjectURL(new Blob(["(" + workerFn.toString() + ")"], { type: "text/javascript" }));
var webworker = new Worker(blobURL);