据我所知,web worker需要写在一个单独的JavaScript文件中,并像这样调用:

new Worker('longrunning.js')

我正在使用闭包编译器来合并和缩小我所有的JavaScript源代码,我不希望将我的worker放在单独的文件中进行分发。有什么办法可以做到吗?

new Worker(function() {
    //Long-running work here
});

既然一级函数对JavaScript如此重要,为什么标准的后台工作方式必须从web服务器加载整个其他JavaScript文件呢?


当前回答

根据您的用例,您可以使用类似

简化的界面,让CPU密集型代码运行在所有核心(node.js和web)

一个例子是

function blocking (exampleArgument) {
    // block thread
}

// turn blocking pure function into a worker task
const blockingAsync = task.wrap(blocking);

// run task on a autoscaling worker pool
blockingAsync('exampleArgumentValue').then(result => {
    // do something with result
});

其他回答

一个更好的阅读方式为内联工人..

    var worker_fn = function(e) 
    {
        self.postMessage('msg from worker');            
    };

    var blob = new Blob(["onmessage ="+worker_fn.toString()], { type: "text/javascript" });

    var worker = new Worker(window.URL.createObjectURL(blob));
    worker.onmessage = function(e) 
    {
       alert(e.data);
    };
    worker.postMessage("start"); 

我认为更好的方法是使用Blob对象,下面你可以看到一个简单的例子。

// create a Blob object with a worker code
var blob = new Blob(["onmessage = function(e) { postMessage('msg from worker'); }"]);

// Obtain a blob URL reference to our worker 'file'.
var blobURL = window.URL.createObjectURL(blob);

// create a Worker
var worker = new Worker(blobURL);
worker.onmessage = function(e) {
  console.log(e.data);
};
worker.postMessage("Send some Data"); 

我喜欢ifbamoq给出的答案,但由于堆栈溢出的积分政策,我无法评论。因此,我将给出一个示例,展示一些正在进行的密集工作——以及它如何不锁定主线程。

如果你像我一样双击html文件,把它们当成小程序,就不会遇到空原点的CORS问题。: -)

<!DOCTYPE html> <html> <head> <title>Worker example: One-core computation</title> </head> <body> <p>The highest prime number discovered so far is: <div id="result"></div></p> </body> <script> // let worker = new Worker('WebWorker.js'); // lets skip this to avoid null origin issues let WorkerFn = (event) => { let isPrime = false; for (let n = 2; n <= 1_000_000; n++) { isPrime = true; for(let i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) isPrime = false; // If you can get thru all this shit and survive, ur prime! if (isPrime) postMessage(n); } } let worker = new Worker(window.URL.createObjectURL(new Blob(["(" + WorkerFn.toString() + ")()"], {type: "text/javascript"}))); worker.onmessage = (event) => { result.innerHTML = event.data; } </script> </html>

我使用这样的代码,你可以将onmessage定义为一个函数而不是纯文本,这样编辑器就可以突出显示你的代码和jshint工作。

const worker = createWorker(); createWorker() { const scriptContent = getWorkerScript(); const blob = new Blob([ scriptContent, ], { type: "text/javascipt" }); const worker = new Worker(window.URL.createObjectURL(blob)); return worker; } getWorkerScript() { const script = { onmessage: function (e) { console.log(e); let result = "Hello " + e.data postMessage(result); } }; let content = ""; for (let prop in script){ content += `${prop}=${script[prop].toString()}`; } return content; }

在worker中运行函数的一行代码:

const FunctionalWorker = fn => new Worker(window.URL.createObjectURL(new Blob(["(" + fn.toString() + ")()"], {type: "text/javascript"})));

使用示例:

let fn = FunctionalWorker(() => {
    self.postMessage("hi");
});
fn.onmessage = msg => {
    console.log(msg);
};