We all know that JS is a single-threaded model. That is to say, only one thing can be handled at a time. The previous things are not finished, and the later things can only be executed after the previous things are finished. With the emergence of multi-core CPU, we can maximize the use of CPU multi-core, to improve js performance.

The Worker interface can create background tasks. That is, you can give JS to run new threads. It is used to process time-consuming and performance-consuming tasks (except asynchronous ones).

  The problem to be solved is
:1. Solve the page deadlock problem. 2. Give full play to the advantages of multi-core CPU to improve JS performance.

I. Specific usage of Web Worker

// The main.js thread passes a number to the worker thread. The worker thread returns a message to the main thread after the calculation.if(window.worker) {// This step is important to check compatibility. // create a worker thread. const myWorker = new Worker("worker.js"); Myworker.postmessage (10000000000); myworker.postMessage (10000000000); //3. Listen to background tasks, myworker.onMessage =function(e) {
	    result.textContent = e.data;
	    console.log('Message received from worker'); } myworker.terminate();} myworker.terminate();} myworker.terminate(); //5. When myWorker is abnormal, the onError event myworker.onerror = will be raisedfunction() {
             console.log('There is an error with your worker! '); }}else{// This step is very important. Specific code according to the need to write their own business. console.log('Your browser doesn\'t support web workers.')}Copy the code

//worker.js worker.js worker.js worker.js worker.js worker.js worker.js worker.js //0 can load other js, such as ajax.'ajax.js'.'b.js'//1. Listen for the main thread onMessage =function(e) {
  console.log('Worker: Message received from main script'); Receives data sent by the master threadletnum = e.data; / / useforCyclic simulation of a time consuming, performance consuming task. (If thisforIf the loop is placed on the main thread, the page will probably freeze, // affecting the user experience).for(leti = 0; i<=num; i++){if(I ==num){//2.'Mission accomplished! '}} //3. Worker threads can also call the close method to terminate worker threads. // close() //4. Similarly, the worker thread can also listen for error messages. onerror =function(err){
    console.log(err)
}Copy the code

Two, use scenarios

Let’s talk about which tasks are appropriate to use Worker. This is the most important point.

1. If it is a program that consumes the main thread performance. Consider using a Web Worker. Prevents pages from getting stuck.

2. Screen pop, Webaudio (views from two groups) www.bilibili.com/ uses Worker. But because the code is compressed, confused, failed to see its detailed use. Please feel free to comment on Worker application scenarios.

Three, notes

1. Non-same-origin restriction (local code can’t be opened in drive mode because there is no source)

The main thread code and Worker thread code must be homologous to work together.

2.DOM and script restrictions

“The context of the Worker thread is different from that of the main thread. The DOM element of the page where the main thread is located cannot be read, and objects such as Document and window cannot be used. However, Worker threads can use navigator, location,XMLHttpRequest. In addition, Worker threads cannot execute alert(), confirm(), and other methods.

3. Prioritize tasks

Worker thread tasks wait for the main thread task to finish.

4. End of the Worker

You can actively close the Worker thread. If it’s a multi-page app, the Worker won’t work without the Worker page.

Four, other

1. Views on Ajax polling in Worker threads.

Ajax is asynchronous, has its own threads, and is compatible. Compatibility needs to be considered if workers are used. So Ajax polling in Worker is not worth the cost. Is not wise.

2. Opinions on creating workers in workers.

It is not recommended because of poor compatibility in Worker creation.


If you think this article is good, you can support it (like + follow); If not, feel free to leave your valuable suggestions in the comments section! Your suggestion is our precious treasure!

Get the full set of NodeJS videos, NodeJS WebSocket, MySQL basic class full set of videos, Phthon videos, dozens of programming e-books, PHP basic videos, Java basic videos and so on! (Reply to ‘Singularity of the World’ on official account)




Related articles

Thoroughly understand files and binary data manipulation

Refer to the article

Developer.mozilla.org/en-US/docs/…

www.ruanyifeng.com/blog/2018/0…