What is a Web Worker

Web workers provide an easy way to run JavaScript scripts in background threads that can perform tasks without interfering with the user interface (they can continue to do whatever they want: click, select content, and so on) without affecting page performance.

You can run any code in the worker thread, with some exceptions. Because workers runs in another global context, so

  • DOM nodes cannot be manipulated directly
  • The Window object cannot be accessed
  • Unable to access the Document object
  • Unable to access the parent object

Functions and classes available to Web Workers

Message mechanism

Data transfer between workers and main thread

  • postMessage(): Sends respective messages
  • onmessage: Response message (event.data)

In this process, data is not shared but copied.

subworker

The worker can generate more workers if needed. These are called subworkers, and they must be hosted within the same parent page. Also, the subworker resolves the URI relative to the parent worker’s address rather than the address of its own page. This makes it easier for workers to record dependencies between them.

Dedicated Web Workers instance

Check whether the browser supports it

if (window.Worker) {
  // ...
}
Copy the code

Create Worker object

Creating a Worker object is simple:

  • callWorker()Constructor of,
  • Specifies the URI of a script
var myWorker = new Worker("worker.js");
Copy the code

Receiving and sending of messages

When the value of input (first and second) changes, the data is passed to the worker:

// main.js
first.onchange = function () {
  // Message posted to worker
  myWorker.postMessage([first.value, second.value]);
};

second.onchange = function () {
  // Message posted to worker
  myWorker.postMessage([first.value, second.value]);
};
Copy the code

After receiving data in worker, the result is thrown back to the main thread after multiplication:

// worker.js
onmessage = function (e) {
  var workerResult = "Result: " + e.data[0] * e.data[1];
  postMessage(workerResult);
};
Copy the code

The main thread also uses onMessage to receive the result:

// main.js
myWorker.onmessage = function (e) {
  // Message received from worker
  result.textContent = e.data;
};
Copy the code

Note: OnMessage and postMessage() must hang on worker objects when used in the main thread, but not when used in workers. The reason is that, within workers, workers are valid global scopes.

To terminate the Worker

Terminate a running worker immediately from the main thread:

myWorker.terminate();
Copy the code

In worker thread, workers can also close themselves:

close();
Copy the code

Sharing the Worker

Note: If the shared worker can be invoked by multiple browse contexts, all these browse contexts must belong to the same origin (same protocol, host, and port number).

A shared worker can be used by multiple scripts — even if these scripts are being accessed by different Windows, iframe, or workers.

Generate a shared worker

var myWorker = new SharedWorker("worker.js");
Copy the code

The biggest difference with dedicated workers is that shared workers must communicate through port objects (an exact open port), which is carried out implicitly in dedicated workers.

Before sending a message, the port connection must be explicitly opened using either the onMessage event handler or the start() method. If the message event is used by the addEventListener() method, select start() to open the port:

myWorker.port.start(); // call in the parent thread
Copy the code
port.start(); // call in the worker thread, assuming the port variable represents a port
Copy the code

Receiving and sending of messages

The postMessage() method must be called by the port object.

First, in the main thread, send a message to the worker:

// main.js
myWorker.port.postMessage();
Copy the code

In worker, the process of receiving messages is complicated:

  • Set when a port connection is created (for example, in a parent thread)onmessageEvent handler function, or call explicitlystart()Method), useonconnectEvent to execute the function
  • Get port (event.ports[0])
  • Add a message handler for the portonmessage(implicitly opens the port connection to the main thread)
// worker.js
onconnect = function (e) {
  var port = e.ports[0];

  port.onmessage = function (e) {
    var workerResult = "Result: " + e.data[0] * e.data[1];
    port.postMessage(workerResult);
  };
};
Copy the code

Finally, receive messages in the main thread:

// main.js
myWorker.port.onmessage = function (e) {
  result2.textContent = e.data;
  console.log("Message received from worker");
};
Copy the code

Chrome: does not allow loading local files

Uncaught SecurityError: Failed to create a worker: script at '(path)/worker.js' cannot be accessed from origin 'null'.
Copy the code

Chrome does not allow Web workers to be loaded when our script is a local file. One solution is to start Chrome with the –allow-file-access-from-files tag, making sure all Chrome Windows are closed before starting.

MacOsX commands:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files
Copy the code

HTML 5 series

  • To understand it
  • Enhanced forms
  • Audio and Video
  • Canvas nanny tutorial (part 1) : Drawing
  • Canvas Nanny tutorial (part 2) : Animation
  • Finally drawing in SVG
  • Geolocation
  • A drag-and-drop operation
  • Understand the Web Worker
  • Understand the Web Storage
  • Understand the WebSocket