This is the 7th day of my participation in Gwen Challenge

What are Web Workers

Web Workers are a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface.[1]

Web Workers is a simple way to run background threads of scripts in Web content. Worker threads can perform tasks without interfering with the user interface.

After reading the above description, you can see that he can create threads (or processes, depending on how workers are implemented in different browsers) in a Web page to perform tasks other than the main program.

Using WebWorker

To use webWorker, it’s easy to start by creating an instance of worker

    new Worker(URL, options);
    /** * It takes two arguments: * URL indicates the URL of the script that the worker will execute. It must abide by the same origin policy options {* * type: 'classic' | 'module', / / used to specify the type of worker DOMString value. * credentials: 'omit' | 'same origin -' | 'include', / / used to designate the worker certificates DOMString value * name: String, / / in the case of DedicatedWorkerGlobalScope, used to show the worker of the scope of a DOMString value, it is mainly used for debugging purposes *} * /
Copy the code

Webworker instances provide two listeners: onMessage and onError. It also provides methods called postMessage, which is used to listen for incoming data, onError, which is used to catch errors, and postMessage, which is used to transmit data to a worker thread. Through these listeners and methods, we can learn the working process of worker as shown in the figure below.

SequenceDiagram main thread ->> Main thread: create worker and add onMessage listener PostMessage worker thread JS->> worker thread JS: determines the corresponding message method and executes the logical worker thread JS->> main thread: postMessage main thread ->> main thread: receives and processes messages

A program can be written according to the sequence diagram:

    // main.js
    const worker = new Worker('worker.js');
    worker.postMessage('hello');
    
    worker.onmessage = function(e) {
      console.log(e.data); // Result: hello
      worker.terminate();
    }
    worker.terminate();
Copy the code
    // worker.js
    self.onmessage = function(e) {
      console.log(e.data); // hello
      var workerResult = 'Result: ' + e.data;
      postMessage(workerResult);
    }
    
Copy the code

The above code is a simple worker workflow. After the main thread creates the worker, load worker.js, worker.js must be the same as the main page!! , after which the worker sends a message to the thread. After the worker.js receives the message, it executes the appropriate code, and then executes window.postMessage to return the data to the main page. The main page fires the onMessage method when it receives the message and terminates the worker thread by calling terminate. At this point, the main page stops communicating with the worker thread

Worker’s global scope

It can be noted that worker is a JS script file, so it can be known that its scope and the main page are independent, that is, they do not share the function and, so web worker cannot change the DOM. As you can see, worker threads have limited functionality compared to the main page. Global methods in worker are [2]:

  1. Minimized Navigator objects, including onLine, appName, appVersion, userAgent, platform properties
  2. Provide a read-only location
  3. Provide setTimeout, setInterval, clearTimeout, clearInterval methods
  4. Provide the XMLHttpRequest

In addition, there are other script files that can be introduced into worker. We can call the importScript() method to accept one or more script files. Again, note that the imported script cannot use code that contains page actions.

Sharing the Worker

The worker described above can only be called by the parent page that generates it, and it is exclusively owned by a home page. Such worker is called a dedicated worker. Besides dedicated worker, there is another kind of worker thread that can be called by multiple home pages, and this worker is called a shared worker. Windows provides the shareWorker class to create shared workers

    // The argument passed is the same as the dedicated worker
    const share = new ShareWorker(URL, options)
    /** * share returns a port attribute * share.port * share.port.start() Open the port for transmission * share.port.end() Close the port for transmission * share.port.postmessage () To send a message, you must first call the share.port.start method */
Copy the code

After learning about sharing workers, let’s write another example

    // main_1.js main page 1
    const share = new ShareWorker('worker.js');
    share.port.start();
    share.port.postMessage('hello');
    // Start receiving messages
    share.port.onmessage = function(e) {
        console.log(e.data); // Result: hello
    }
    
    // worker.js
    onconnect = function(e) {
        const main_1 = e.port[0];
        main_1.onmessage = function(e) {
            main_1.postMessage(`Result: ${ e.data }`); }}Copy the code

summary

This paper mainly introduces the concept and function of Web workers.

If you find this article helpful, you can encourage the author by clicking a “like”, and if you want to learn more about JavaScript or Node, you can click here.

Please point out any inaccuracies or errors in the comments section.

reference

  1. Web Workers
  2. JavaScript advanced programming