There are several considerations for using Web workers.
(1) Homologous restriction
The script file assigned to the Worker thread must be of the same origin as the script file of the main thread.
(2) DOM restriction
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 restrictions
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. Example:
export const createWorker = f= > {
let pendingJobs = {}
const worker = new Worker(URL.createObjectURL(new Blob([
`onmessage = ({ data: { jobId, params } }) => {
const result = (${f.toString()}) (... params) postMessage({ jobId, result }) }`
])))
worker.onmessage = ({ data: { result, jobId } }) = > {
// Call resolve to change the Promise state
pendingJobs[jobId](result);
// Delete to prevent key conflicts
delete pendingJobs[jobId];
}
return (. params) = > new Promise(resolve= > {
const jobId = String(Math.random());
pendingJobs[jobId] = resolve;
worker.postMessage({ jobId, params })
})
}
Copy the code
/ / use the worker
import { createWorker } from './worker.js'
const handleLoopDataShow = param= > {
let data = [];
param.map((item) = > {
data = data.concat(item);
});
return data;
}
const showWorker = createWorker(handleLoopDataShow);
showWorker(arr).then(val= > {
console.log ('do somethings');
});
Copy the code
Refer to the article: zhuanlan.zhihu.com/p/83001302