前言
虽然worker可以将复杂的运算放入单独线程去运算,不阻塞UI线程,但是,由于worker()的构造函数的参数不能读取本地的文件,只能来自网络,所以当在一个项目里想使用本地的模块函数,是一个很麻烦的过程,官方的方法也没有提供方便的做法。
解决方法
将函数转换为blob,然后生成URL对象。
function fn2workerURL(fn) { var blob = new Blob([\'(\'+fn.toString()+\')()\'], {type: \'application/javascript\'}) return URL.createObjectURL(blob) }
这样就可以直接在调用本地模块文件了。
demo
// worker.js function scope() { function timedCount(e) { postMessage(e - 0 + 1); } onmessage = function (oEvent) { console.error(\'worker error \', oEvent); timedCount(oEvent.data); }; } function fn2workerURL(fn) { var blob = new Blob([\'(\' + fn.toString() + \')()\'], {type: \'application/javascript\'}); return URL.createObjectURL(blob); } export default fn2workerURL(scope);
// main.js ... import workerUrl from \'./worker.js\'; startWorker = () => { if (typeof(Worker) !== \'undefined\') { if (!w) { w = new Worker(workerUrl); } w.postMessage(\'1\'); w.onmessage = function (event) { console.error(\'worker message: \', event.data); }; } else { alert(\'dont support worker\'); } };