Web workers

suggest change

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 and other values the structured clone algorithm rejects) 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:

const webworker = new Worker("./path/to/webworker.js");

It’s also possible to create a Worker dynamically from a string using URL.createObjectURL(). The string below is wrapped in parentheses, and that text is not a valid worker script, so the worker fails to load:

const workerData = "function someFunction() {}; console.log('More code');";

const blobURL = URL.createObjectURL(new Blob(["(" + workerData + ")"], { type: "text/javascript" }));

const webworker = new Worker(blobURL);

The same method can be combined with Function.toString() to create a worker from an existing function. The blob is only the function expression. Nothing calls it, so "I was run" is not logged:

const workerFn = function() {
    console.log("I was run");
};

const blobURL = URL.createObjectURL(new Blob(["(" + workerFn.toString() + ")"], { type: "text/javascript" }));

const webworker = new Worker(blobURL);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents