What is a Web Worker?

JavaScript language adopts the single-thread model, that is, tasks can only be completed on one thread, one thing can only be done at a time, the previous task is not completed, the following tasks can only be queued, due to the emergence of multi-core CPU, single-thread brings great inconvenience, can not give full play to the ability of the computer.

Web workers are created for javascript to create multiple threads. The main thread creates Worker sub-threads and assigns some tasks to the background. After the sub-threads complete the calculation tasks, the results are returned to the main thread. The main thread will be smooth. Page loading display can be divided into two parts: the main process is also called UI process, child process is also called worker process, child process can not control THE UI process, only data interaction.

Web Worker child threads, once created, are always running independently of other scripts and are not interrupted by activity on the main thread. This facilitates communication that responds to the main thread at any time. However, this also causes the Worker to consume resources, so it should not be overused and should be closed after use.

Using Web Worker

  1. Origin restriction: Scripts assigned to Worker threads must be of the same origin as the script file of the main thread, otherwise there will be cross-domain problems.
  2. DOM restriction: Unlike the main thread, the global object on which the Worker thread resides cannot read the main thread’s DOM object or use window, Document, parent objects. But Worker threads can use navigation and Location objects.
  3. Data communication: Worker thread and main thread are not in the same environment and cannot communicate directly. Data communication must be completed through messages.
  4. Script restriction: Worker threads cannot execute window alert and confirm methods. However, requests can be sent via Ajax.
  5. File restrictions: Worker threads cannot read local files, and scripts loaded by child threads must come from the network.

2. Use grammar

2.1 Creating Worker threads:

Before creating the worker, check that your browser supports it. Using Typeof check, the code is as follows:

if( typeof Worker ! == undefined){console.log(" support Worker threads ")}else{console.log(" support Worker threads ")}Copy the code

After checking that the browser supports workers, the main thread uses the new command to call the worker() constructor to create a new worker thread.

var myWorker = new Worker('worker.js')
Copy the code

The constructor takes a script file, which cannot be a local file but must come from a network script, which is the task to be executed by the Worker thread. If the file fails to load, the Worker will fail.

2.2 Data communication between main thread and child thread:

The main thread calls the postMessage() method to send a message to the Worker. The parameter in the postMessage(parameter) method is the data passed to the Worker, which can be in any format.

MyWorker. PostMessage (" hello ")Copy the code

The Worker thread then receives the message by specifying a listener function via onMessage. The worker.js code is as follows:

This. onMessage = function(res){console.log(" received message ",res.data) this. onMessage (" RECEIVED message ")}Copy the code

Once the worker child process receives the message, it can continue sending messages to the main process using postMessage(). Code as above.

The main process also receives messages through the onMessage listener.

Myworker. onMessage = function(res){console.log(" Main thread received message: ",res.data)}Copy the code

2.3 Worker thread

Inside the Worker thread, add the this. onMessage listener function, where this is the global object of the child thread and can also be replaced with self, where self stands for the child thread itself. Is equal to:

Self. onMessage "=" this.onmessageCopy the code

In addition to specifying listener functions with self.onMessage, you can also use this.addeventListener () to listen on event objects. The worker.js code above can be changed to:

This.addeventlistener ("message",function(res){console.log("res",res.data)} addEventListener("message",function(res){ this.console.log("1",res.data) })Copy the code

2.4 Error Handling

The main thread can monitor whether the Worker has an error. If an error occurs, the Worker will trigger the error event of the main thread.

/ / write a myWorker. Onerror = function (e) {the console. The log (' e 'and e)} / / write two myWorker addEventListener (" error ", the function (e) { console.log("e",e) })Copy the code

Worker child threads can also listen for error events.

2.5 close the Worker

Worker consumes resources and should not be overused. It should be closed after being used. Both the main thread and child threads can be closed.

Myworker.terminate () // The child thread closes self.close() // this.close() // method 2Copy the code

3. Web Worker of the same page

Typically, workers load a separate javascript file, but they can also load code on the same page as the main thread. When adding Worker scripts to web pages, it is necessary to specify that the type attribute of script tag is a value unknown to the browser, otherwise it will lose meaning. Such as:

<script type="app/worker" id=" WRS "> this.onmessage = function(res){console.log(" receive parameters ",res.data)} </script>Copy the code

Then, this code needs to be read. First, the script code embedded in the webpage is converted into a binary object, and then the URL is generated for the binary object, and then the worker loads the URL. In this way, the main process and the worker are in the same webpage. The code is as follows:

<script> var blob = new Blob([document.querySelector("#wrs").textContent]); var url = window.URL.createObjectURL(blob); Var worker = new worker (url) worker.postmessage (" send data ") </script>Copy the code

Iv. Summary of Worker attributes and methods

The Worker constructor method:

  • Worker.postmessage () – Sends messages.
  • Worker.onmessage() – Listens for data sent by child threads.
  • Worker.onmessageerror() – Event raised when sending data cannot be serialized.
  • Worker.onerror() – Error handling.
  • Worker.terminate() – Terminates the Worker.

Child process property methods:

The Worker() constructor, which can take two arguments, the first being the address of the script and the second being the configuration object, which specifies the name of the Worker. Such as:

var myWorker = new Worker('worker.js', { name : 'myWorker' });
Copy the code
  • Self. name – The name of the Worker
  • Self. onMessage – Receives a message
  • Self. postmessage – Sends data
  • Self. onerror – Error handling
  • Self. onMessageError – Raised when sent data cannot be serialized into a string
  • Self. close – Closes the Worker thread
  • Self.importscript () – Loads the JS script