SoFunction
Updated on 2025-04-12

Understand JavaScript multithreaded Web Worker in one article

Preface

As we all know, JavaScript is single-threaded, which means that all tasks can only be completed on one thread and can only do one thing at a time. If the previous task is not completed, you can only wait later. Therefore, HTML5 proposed the web Worker standard, indicating that JavaScript allows multiple threads, but the child thread is completely controlled by the main thread, and the child thread cannot operate the DOM, and only the main thread can operate the DOM. Therefore, the best use scenario for Web Worker is to perform some data processing or computing tasks with high overhead. Next, let’s learn more about this thing~

text

What is a Web Worker?

Web Worker is part of the HTML5 standard, a specification that defines an API that allows a JavaScript program to run in another thread outside the main thread.

It is worth noting that two types of worker threads are defined in the Web Worker specification, namely the dedicated thread Dedicated Worker and the shared thread Shared Worker. Among them, Dedicated Worker can only be used for one page, while Shared Worker can be shared by multiple pages.

How to use Worker?

Several things to pay attention to when using

  • Homologous restriction
    The script file assigned to the Worker thread running must be of the same origin as the script file of the main thread.
  • DOM Limitations
    The global object where the Worker thread is located is different from the main thread. It cannot read the DOM object of the web page where the main thread is located, nor can it use objects such as document, window, and parent. However, Worker threads can navigator objects and location objects.
  • Communication
    The Worker thread and the main thread are not in the same context, so they cannot communicate directly and must be done by publishing a subscription message.
  • Script restrictions
    The alert() method and confirm() method cannot be executed in the Worker thread, but the AJAX request can be sent using the XMLHttpRequest object.
  • File restrictions
    The Worker thread cannot read the local file, that is, it cannot open the local file system (file://). The script it loads must come from the network.

How to create a Worker?

Worker constructor, the first parameter is the script's URL (the same-origin policy must be followed). This parameter is required and can only load JS scripts, otherwise an error will be reported.
The second parameter is the configuration object, which is optional. One of its functions is to specify the name of the Worker, which is used to distinguish multiple Worker threads.

For example, create a Worker

const worker = new Worker('');

How does the main thread communicate with the child thread?

The basic principle is to load a read-only file in the current main thread to create a new thread. The two threads exist at the same time and do not block each other. It provides data exchange interfaces between the child thread and the main thread postMessage and onmessage.

For example, send a message to a Worker child thread

// The first method of delivery('I'm the main thread');

// The second method of delivery({
  // ArrayBuffer object 
  input: buffer
}, [buffer]);

The parameters of the () method are the data passed to the child thread Worker. It can be of various data types, including binary data.

Receive messages sent back by child thread Work

 = function (event) {
  ('Subthread message:' + )
}

The child thread sends a message to the main thread

('I'm a child thread')

Receive messages from the main thread

 = function (event) {
  ('Main thread's message:' + )
}

self represents the child thread itself, that is, the global object of the child thread.

The following are the common APIs for main thread and child threads

In the main thread, the worker indicates that it is an instance of the Worker:


  • The main thread sends a message to the worker thread. The message can be any type of data, including binary data.

  • The main thread closes the worker thread

  • Specify the callback when the worker thread sends a message
    It can also be done by ('message', cb)

  • Specify the callback when an error occurs in the worker thread
    Also OK ('error', cb)

The global object in the Worker thread is self, representing the child thread itself. At this time, this points to self:


  • The worker thread sends messages to the main thread. The message can be any type of data, including binary data

  • Worker thread closes itself

  • Specifies the callback when the main thread sends worker thread message
    It's OK ('message', cb)

  • Specify the callback when an error occurs in the worker thread
    Also ('error', cb)

  • Worker's name. This property is read-only and is specified by the constructor.

Loading tool function

importScripts('', '', ...)

importScripts is a synchronous method, and once the importScripts method returns, you can start using the loaded script without the need for a callback function.

Shared Thread SharedWorker

Shared threads are to avoid the repeated creation and destruction of threads and reduce the consumption of system performance. Shared thread SharedWorker can have thread links on multiple pages at the same time.
Use SharedWorker to create a shared thread, and you also need to provide a URL address or blob of a javascript script file. The script file contains the code we need to execute in the thread, as follows:

const sharedworker = new SharedWorker("");

The shared thread also uses the message event to listen for thread messages, but uses the port attribute of the SharedWorker object to communicate with the thread as follows.

 = function (event) {
  ()
}

You can also use the port attribute of the SharedWorker object to send messages to the shared thread.

('Hello World');

This is the end of this article about understanding JavaScript multithreaded Web Worker. For more related JavaScript multithreaded Web Worker content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!