web worker在react项目中的使用
新建一个worker.js文件,编写worker子线程脚本,代码如下:
const workercode = () => { self.onmessage = function(e) { console.log('Message received from main script'); var workerResult = 'Received from main: ' + (e.data); console.log('Posting message back to main script'); self.postMessage(workerResult); // here it's working without self } }; // 把脚本代码转为string let code = workercode.toString(); code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}")); const blob = new Blob([code], {type: "application/javascript"}); const worker_script = URL.createObjectURL(blob); module.exports = worker_script;
按照上述方式,创建好worker_script,在react项目组件中引用时只需要在对应的组件文件中:
import worker_script from './worker'; var myWorker = new Worker(worker_script); myWorker.onmessage = (m) => { console.log("msg from worker: ", m.data); }; myWorker.postMessage('im from main');