Worker Usage Scenarios

Js runs in a single thread, which may block the loading of the page and cause the page to feign dead when encountering some JS that need to process a large amount of data. At this point, we can use worker to open up a child thread independent of the main thread to perform a lot of operations. This will not cause the page to freeze. It also indicates that worker can be used to solve the problem of page jam caused by a large number of operations.

The worker of grammar

const worker=new Worker(aURL, options)
Copy the code

It takes two arguments:

AURL (must) is the URL of a script that DOMString represents that the worker will execute. It must comply with the same origin policy.

Options (Optional) One of its functions is to specify the name of the Worker, which is used to distinguish multiple Worker threads

The properties of the worker

Worker.onerror: Specifies a listener for error events

Worker. onMessage: Specifies the listener function for the message Event. The sent data is in the Event.

Worker. onMessageError: Specifies a listener function for messageError events. This event is emitted when the sent data cannot be serialized into a string.

The method of the worker

Worker.postmessage () : sends a message to the Worker thread.

Worker.terminate() : Terminates the Worker thread immediately.

Use worker’s attention points

1. Origin restriction The script files assigned to Worker threads must be the same origin as the script files of the main thread.

2.DOM limits the global object where the Worker thread is located. Unlike the main thread, DOM objects of the page where the main thread is located cannot be read, and objects such as Document, window and parent cannot be used. However, Worker threads can have navigator objects and Location objects.

3. Communication the Worker thread and the main thread are not in the same context. They cannot communicate directly and must be completed through messages.

4. The script restricts Worker threads from executing the alert() and confirm() methods, but can make AJAX requests using the XMLHttpRequest object.

5. File restriction Worker threads cannot read local files, that is, they cannot open the local file system (file://), and the scripts it loads must come from the network.

The implementation places the worker main thread and child thread code in the same file

Typically, workers load a separate JavaScript script file, but they can also load code on the same page as the main thread.

<script id="worker" type="app/worker"> //*type specifies a type that the browser does not recognize
        self.onmessage = function (event) { // The child thread receives the method triggered by the main thread passing data
            var data = event.data; 
            var ans = fibonacci(data); 
            this.postMessage(ans); // Submit data to the main thread after the request is completed or processed
        };
        function fibonacci(n) { // The method to be executed by the child thread is to request a large amount of data, in this case a recursive method
              return n < 2 ? n : arguments.callee(n - 1) + arguments.callee(n - 2);
        }
</script>
<script>
    var blob = new Blob([document.querySelector('#worker').textContent]);/ / code
    var url = window.URL.createObjectURL(blob);  // compile to url
    var worker = new Worker(url); // Because workers can only request network data. So you need to compile to a URL
    worker.postMessage(40);// Pass data to child threads
    worker.onmessage=function(event){ // Receive the data passed by the child thread
        var data=event.data;
        console.log(data) / / print
    };
    worker.onerror=function(event){ // When an error is encountered, the error message is printed to view
        console.log(event.fileName,event.lineo,event.message);
    };
</script>
Copy the code

Self represents the child thread, the global object of the child thread, because in different contexts you can also use the this reference

Note that the type attribute of the

reference

MDN

Web Worker Tutorial