Some background reasons
In the history of asynchrony, this time it will! Because the JS engine is single-threaded, we need to program asynchronously, and we need to process time-consuming operations asynchronously. However, when these tasks are executed asynchronously, they are placed in the browser’s event task queue and are executed on a first-in-first-out basis when the execution stack is idle, but they are still single-threaded. Complex and time-consuming tasks can still take a lot of time.
In order to make the JS engine multi-threaded, webworker came into being. Of course, JS itself is still single-threaded, but the browser in which JS runs provides multi-threading for it.
What is a WebWorker ❓
The official documentation
Using Web Workers, a Web application can run a scripted operation in a background thread independent of the main thread. The advantage of this is that time-consuming processing can be performed in a separate thread, allowing the main thread (usually the UI thread) not to be slowed down by blocking.
Benefits:
-
Worker threads are created and run for a long time
-
It will not be interrupted by activities on the main thread, such as the user clicking a button or submitting a form
-
It facilitates the communication of the main thread at any time, and at the same time ensures the timely response of the page to the user.
Disadvantage:
Worker consumes resources and should not be overused. Please close it immediately after using it.
Some big holes:
1. Do not cross domains
The script file assigned to the Worker thread must be of the same origin as the script file of the main thread.
2. The DOM
Unlike the main thread, the global object where the Worker thread is located cannot read the DOM object of the page where the main thread is located, nor can document, window, parent objects be used. However, Worker threads can have navigator objects and Location objects.
3. Correspondence
The Worker thread and the main thread are not in the same context; they cannot communicate directly and must be done via messages.
4. Script limitations
Worker threads cannot execute the Alert () and Confirm () methods, but can make AJAX requests using the XMLHttpRequest object.
5. 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.
How do you use the 😈 WebWorker
Basic usage
1. Create a Worker thread
// const myWorker = new Worker(aURL, options); AURL :js file name [options] Some propertieslet myWorker = new Worker("worker.js"); // It is not allowed to read local files in Chrome, so it is better to start a local server to read or read cognate network filesCopy the code
2. Thread communication
Onmessage: listening event postMessage: sending event
Main thread file
// When a time-consuming event is triggered first.onchange =function() {
myWorker.postMessage([first.value,second.value]);
console.log('Message posted to worker');
}
second.onchange = function() {
myWorker.postMessage([first.value,second.value]);
console.log('Message posted to worker');
}
Copy the code
worker.js
self.onmessage = function(event){
console.log('Worker recieved message');
};
Copy the code
3. Close at the end
Main thread file
myWorker.terminate();
Copy the code
Child thread file
self.close();
Copy the code
4. Error handling
The main thread can listen for Worker errors. If an error occurs, the Worker fires an error event for the main thread
// myworker.onerror (function(event) { }); / / 2: myWorker. AddEventListener ('error'.function (event) {
});
Copy the code
5. Load other files
There is a special method inside the Worker to load other scripts. ImportScripts ()
importScripts(); /* imports nothing */
importScripts('foo.js'); /* imports just "foo.js" */
importScripts('foo.js'.'bar.js'); /* imports two scripts */
importScripts('//example.com/hello.js'); /* You can import scripts from other origins */
Copy the code
6. Data communication between threads
The communication between the main thread and the worker is a process of value copy, that is, value transmission rather than address transmission. Parse json.parse is actually done after json.stringify. Copying in this way can cause performance problems. For example, if the main thread sends a 500MB file to the Worker, by default the browser will generate a copy of the original file. To solve this problem, JavaScript allows the main thread to transfer binary data directly to child threads, but once it is transferred, the main thread can no longer use the binary data, to prevent the troublesome situation of multiple threads modifying the data at the same time. This method of transferring data is called Transferable Objects. This enables the host thread to quickly deliver data to the Worker, which is very convenient for image processing, sound processing, 3D computing, etc., without performance burden.
var transfer = new ArrayBuffer(1);
worker.postMessage(transfer, [transfer]);
Copy the code
The use of WebWorker
1. Huge and complex mathematical calculations
2. Image processing
By using the data obtained from
3. Requests for large amounts of data
4. Background data analysis
Since we have more potential CPU time available when using Web workers, we can now consider new application scenarios in JavaScript. For example, we can imagine processing user input in real time without affecting the UI experience. Taking advantage of this possibility, we can imagine an application like Word (Office Web Apps suite) that looks up a dictionary in the background as the user types, helps the user automatically correct errors, and so on
🌰 give it a try
Git address note: you must use http-server to open the file
reference
Official document Ruan Yifeng teacher’s blog talk about Webworker ⬅️ the excellent writing and online demo suggest reading the full text