reference
Web Workers literature review
Web Workers | MDN
instructions
Browser multithreading technology to ease page lag, improve application performance. [Multi-core, multi-thread concurrency] Web workers create threads at the operating system level, independent of the main thread js running environment.
Simple Communication Example
The main thread communicates with the worker thread via messageEvent, simple example.
- In the main thread
const worker = new Worker('./worker.js'); / / worker. Js address
worker.postMessage('walker'); // The main thread sends a message to the worker
// Respond to postMessage in worker
worker.onmessage = (e) = > {
console.log('Walker responded:', e.datas)
};
Copy the code
- In the worker
// Respond to a message from the main thread
onmessage = (e) = > {
console.log('I received a message from the master thread:', e.data)
postMessage('to')}Copy the code
Termination of the thread
- Terminating the worker in the main thread:
myWorker.terminate();
- Terminating in worker:
close();
Handling errors
When the worker encounters an in-process error, its onError event handler will be called.
Multiple worker processes
Workers can generate more workers, which is called subworkers, and they must be hosted in the same parent page. Also, the subworker resolves the URI relative to the parent worker’s address rather than the address of its own page. This makes it easier for workers to record dependencies between them.
Content security Policy
Because worker has its own execution context and is not limited to Document, to specify a content safety policy for worker, it is necessary to add a content safety policy to the request sending worker code.