[Front-end] Application of WebWorker in front-end SPA framework

1. What is WebWorker

Concept: Web Worker is a JavaScript script that runs in a web browser. It can run in a background thread without blocking the main thread. This means that Web Workers can perform complex computational tasks in the background without affecting the responsiveness of the user interface
in addition to standardJavaScript< a i=3> function set (such as String, Array, a>, etc.), you can run anything you like in the worker thread code, with some exceptions: you cannot directly manipulate DOM elements in the worker thread, or use certain methods and properties in the Window object. JSON, Object

Second,Worker type

There are many different types of workers:

  1. A dedicated worker is a worker used by a single script. The context is represented by a DedicatedWorkerGlobalScope object.
  2. SharedWorker is a worker that can be used by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complicated than dedicated workers - scripts must communicate over active ports.
  3. Service_Worker basically acts as a proxy server between the web application, the browser, and the network (if available). Their purpose is (among other things) to create an efficient offline experience, intercept network requests, and take appropriate actions based on network availability and update resources residing on the server. They will also allow access to push notifications and background sync APIs.

3. Dedicated Worker

Properties: Accessible only by the script that created it

  1. Create a worker
    const myWorker = new Worker(‘worker.js’);
  2. You can handle it through the postMessage method and onmessage The function triggers the worker's method. When you want to send a message to a worker, you just do this (main.js)
first.onchange = () => {
    
    
  myWorker.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

second.onchange = () => {
    
    
  myWorker.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};
myWorker.onmessage = (evt)=>{
    
    	console.log(evt.data)}
  1. How to write worker scripts
self.onmessage = (evt)=>{
    
    		console.log(evt.data)}
self.postMessage("message")
  1. Terminate worker
myWorker.terminate();

4. Precautions for use

  1. DOM objects cannot be accessed in worker scripts
  2. The window object of worker and the window object in the main process are not the same global object
  3. worker postMessage cannot send Object object that cannot be serialized.
  4. Woker can import objects through the importScript method
    a)importScript(“path”)

5. How to apply the worker program in the front-end SPA framework

In the SPA framework, modules need to be imported through commonjs or requirejs, and the script in the worker is usually not a standard module, so it cannot be imported in the normal way. There are two common solutions.

  1. Convert the worker script to a binary blob file and then export it through export
    Insert image description here

  2. Introducing worker-loader into webpack, the worker imported through loader can import new modules through import in script scripts.
    Insert image description here

6. Specific usage scenarios

  1. In the electronic scenario of paper books, the introduction of a large number of boxes and forms requires data merging and processing. Conventional processing methods will inevitably cause certain blocking and performance problems for rendering threads such as GUI and JS to a certain extent. Therefore, we Introducing workers to handle this large amount of calculations

Insert image description here

  1. The usage in the project code is as follows

a)Insert image description here

b)Insert image description here

7. Summary

Web Workers are suitable for use in the following scenarios:

  1. Multi-threaded computing tasks: When a large amount of calculations, data processing or intensive operations need to be performed on a web page, Web Workers can handle these tasks in a background thread to avoid blocking the main thread and improve the responsiveness and fluency of the page.
  2. Long-running tasks: Some tasks may take a long time to complete, such as image processing, audio and video encoding and decoding, etc. Using Web Workers allows these tasks to be performed in the background without affecting the user's interaction with the page.
  3. Network requests: When performing a large number of network requests, Web Workers can be used to share the work load of the main thread, thereby preventing the page from becoming stuck due to excessive network requests.
  4. Complex animation: For complex animation effects, the calculation part can be handed over to Web Workers to improve the smoothness and performance of the animation.
  5. Large-scale data processing: When large-scale data sets need to be processed, Web Workers can help process data in parallel and improve the efficiency of data processing.
  6. Real-time communication: Use Web Workers to implement real-time communication protocols such as WebSocket or WebRTC to achieve real-time two-way communication with the server.
    It should be noted that Web Workers cannot directly access the DOM because they run in an independent context and cannot access the variables and functions of the main thread. Therefore, Web Workers are mainly used to handle computationally intensive tasks and DOM-independent background processing. If you need to interact with the DOM, you can use postMessage to communicate with the main thread to achieve the purpose of data exchange.

おすすめ

転載: blog.csdn.net/qq_43585322/article/details/132732405