(進入項目頁面,裏面的original-version目錄下就是做者的最初的代碼)webpack
var worker =new Worker('work.js’)
可是 @simon3000 的建議讓我眼前一亮!他告訴我,根據他使用webworker-loader(webpack技術棧)的經驗,有一種連續轉換的方式能夠直接將一個普通函數變成WebWorkergit
// 文件名爲main.js function work () { onmessage = ({data: {message}}) => { console.log ('i am worker, receive:' + message); postMessage ({result: 'message from worker'}); }; } const runWorker = f => { const worker = new Worker ( URL.createObjectURL (new Blob ([`(${f.toString ()})()`])) ); worker.onmessage = ({data: {result}}) => { console.log ('i am main thread, receive:' + result); }; worker.postMessage ({message: 'message from main thread'}); }; const testWorker = runWorker (work);
// 文件名爲index.js function work () { onmessage = ({data: {jobId, message}}) => { console.log ('i am worker, receive:-----' + message); postMessage ({jobId, result: 'message from worker'}); }; } const makeWorker = f => { let pendingJobs = {}; const worker = new Worker ( URL.createObjectURL (new Blob ([`(${f.toString ()})()`])) ); worker.onmessage = ({data: {result, jobId}}) => { // 調用resolve,改變Promise狀態 pendingJobs[jobId] (result); // 刪掉,防止key衝突 delete pendingJobs[jobId]; }; return (...message) => new Promise (resolve => { const jobId = String (Math.random ()); pendingJobs[jobId] = resolve; worker.postMessage ({jobId, message}); }); }; const testWorker = makeWorker (work); testWorker ('message from main thread').then (message => { console.log ('i am main thread, i receive:-----' + message); });