欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

web worker在react项目中的使用:

程序员文章站 2022-03-05 08:10:47
...

web worker在react项目中的使用:

方法一:

笔者尝试过worker-loader软件包(https://github.com/webpack-contrib/worker-loader)。用法如下:

import Worker from 'worker-loader!../workers/myworker.js';

然而不幸的是,会遇到报错,告诉我Create React App不支持Webpack加载器之类的。

方法二(成功可用):

新建一个worker.js文件,编写worker子线程脚本,代码如下:

// 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');

经测试,完美可用!

相关标签: javascript reactjs