As we all know:
The JavaScript language uses a single-threaded model, which means that all tasks can only be done on one thread, one thing at a time. The first task is not finished, the next task has to wait. With the enhancement of computer computing ability, especially the emergence of multi-core CPU, single thread brings great inconvenience and can not give full play to the computing ability of the computer.
The function of Web Worker is to create a multithreaded environment for JavaScript, allowing 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.
Basic usage:
1. Based on HTML, CSS, JS three king Kong, here guide ruan Dasen Blog
Web Worker Tutorial
2. Web worker configuration based on Webpack
Since the mainstream development mode is now migrating to the SPA framework, the traditional new Worker() cannot be constructed normally, which requires the worker-Loader plug-in to process.
According to the NPM document of worker-Loader, workers can be used normally in WP projects. However, the author is all in TS, so certain processing needs to be done for TS.
The specific operation process is as follows:
1. Import the worker-loader NPM package
npm install worker-loader
Copy the code
2. Configure the loader
{
test: /\.worker\.(c|m)? js$/i,
use: [{
loader: "worker-loader",}}]Copy the code
3. Declare the index.d.ts file again
declare module "worker-loader! *" {
// You need to change `Worker`, if you specified a different value for the `workerType` option
class WebpackWorker extends Worker {
constructor();
}
// Uncomment this if you set the `esModule` option to `false`
// export = WebpackWorker;
export default WebpackWorker;
}
Copy the code
4. Create the *.worker.ts file
const ctx: Worker = self as any;
// Post data to parent thread
ctx.postMessage({ foo: "foo" });
// Respond to message from parent thread
ctx.addEventListener("message".(event) = > console.log(event));
Copy the code
5. The main file references worker
import Worker from "worker-loader! ./Worker";
const worker = new Worker();
worker.postMessage({ msg: 1 });
worker.onmessage = (event) = > {};
worker.addEventListener("message".(event) = > {});
Copy the code