Introduction to Web Workers:

Create a multithreaded environment for JavaScript that allows the main thread to create Worker threads and assign some tasks to the latter to run. While the main thread is running, the Worker thread is running in the background without interfering with each other. Wait until the Worker thread completes the calculation and returns the result to the main thread. The advantage of this is that when computationally intensive or high-latency tasks are taken on by Worker threads, the main thread (usually responsible for UI interactions) will flow smoothly and will not be blocked or slowed down.

There are several points to note when using Web workers:

  • Workers are resource-intensive and should not be overused, and should be shut down once used

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

  • DOM restriction: The Worker cannot read the DOM object of the page where the main thread is located, nor can it use objects such as Document, window, and parent. However, Worker threads can have navigator objects and Location objects.

  • Communication: The Web worker communicates with the main thread via postMessage

  • Scripting limitation: Worker threads cannot execute alert() and Confirm () methods, but can make AJAX requests using XMLHttpRequest objects.

  • File restrictions: the Worker thread cannot read local files, that is, cannot open the native file system (file://), and the scripts it loads must come from the network.

Web workers have two characteristics:

  • It can only serve the newly created pages, and different pages cannot share the same Web Worker. A service worker serves multiple pages

  • When the page is closed, the new Web Worker on the page will also be closed and will not stay in the browser permanently. A service worker has a longer life cycle than a Web worker and survives after the page is closed.

Basic usage:

<script type="text/javascript"> const worker = new worker ('./worker.js'); // Use new Worker to create worker.postMessage('Hello World'); worker.onmessage = function (event) { console.log('Received message ' + event.data); doSomething(); } function doSomething() {worker.postmessage ('Work done! '); worker.terminate(); This. AddEventListener ('message', function (e) {this. PostMessage ('You said: ' + e.data); }, false); Self. addEventListener('message', function (e) {postMessage('You said: '+ e.data); }, false); You can use self.close() to close itselfCopy the code

The Web worker cannot load the local problem, so it can be resolved as follows:

<script id="getWorker" type="javascript/worker"> this.addEventListener('message', Function (e) {this.postmessage (' I have worker files' + e.data); }, false); </script> <script> let workerBlob = new Blob([document.getElementById('getWorker').textContent]) let worker = new Worker(window.URL.createObjectURL(workerBlob)) worker.postMessage('Hello World'); worker.onmessage = function (event) { console.log('Received message ' + event.data); doSomething(); } function doSomething() {worker.postmessage ('Work done! '); worker.terminate(); } </script>Copy the code

Some properties and notes of Web workers:

  • ImportScripts () : Internally loads other scripts, or multiple scripts

    ImportScripts (‘ script1. Js’); importScripts(‘script1.js’, ‘script2.js’);

  • Error handling: The Worker raises error events for the main thread.

    worker.onerror(function (event) { // … }); Worker. addEventListener(‘error’, function (event) {//… });

  • Location: The location property returns the WorkerLocation object associated with the thread when it is created, which represents the absolute URL of the footstep resource used to initialize the worker thread. This URL resource location does not change even after the page is redirected multiple times.

  • XMLHttpRequest: This is used to make Ajax requests

  • SetTimeout /setInterval: delay execution and timed execution of functions, the same as window objects. AddEventListener/postMessage: first to register to monitor events, and the window object of the same, is not in now. PostMessage, also described above, is a method of communication between the main thread and child threads.

MessageChannel implements communication between workers:

Not only the main thread and Worker thread can communicate, but also different workers can communicate, which can be realized by MessageChannel