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

new Worker('longrunning.js')

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

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

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


当前回答

http://www.html5rocks.com/en/tutorials/workers/basics/#toc-inlineworkers

如果您希望动态地创建工作人员脚本,或者创建一个自包含的页面,而不必创建单独的工作人员文件,该怎么办?使用Blob(),您可以通过将工作代码的URL句柄创建为字符串,将工作代码“内联”到与主逻辑相同的HTML文件中


BLOB inline worker的完整示例:

<!DOCTYPE html> <script id="worker1" type="javascript/worker"> // This script won't be parsed by JS engines because its type is javascript/worker. self.onmessage = function(e) { self.postMessage('msg from worker'); }; // Rest of your worker code goes here. </script> <script> var blob = new Blob([ document.querySelector('#worker1').textContent ], { type: "text/javascript" }) // Note: window.webkitURL.createObjectURL() in Chrome 10+. var worker = new Worker(window.URL.createObjectURL(blob)); worker.onmessage = function(e) { console.log("Received: " + e.data); } worker.postMessage("hello"); // Start the worker. </script>

其他回答

我认为更好的方法是使用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"); 

@Trincot's似乎是目前为止最好的。然而,也许我们可以进一步发展它。所以我的想法是,

我们不要修改Function.prototype。 为线程操作获取函数的承诺/线程化版本。 如果需要,请确保仍然可以同步调用该函数。

因此,我们用spawn方法定义了Threadable类。一旦我们将函数设为该类的成员,那么它就是可线程的:)

class Threadable extends Function { constructor(f){ super("...as",`return ${f.toString()}.apply(this,as)`); } spawn(...as){ var code = `self.onmessage = m => self.postMessage((${this.toString()}).apply(self,m.data));`, blob = new Blob([code], {type: "text/javascript"}), wrkr = new Worker(window.URL.createObjectURL(blob)); return new Promise( (v,x) => ( wrkr.onmessage = m => (v(m.data), wrkr.terminate()) , wrkr.onerror = e => (x(e.message), wrkr.terminate()) , wrkr.postMessage(as) ) ); } } function add(...nums) { return nums.reduce((a,b) => a+b); } var addT = new Threadable(add); addT.spawn(1,2,3,4) .then(m => console.log(`Promisified thread returned ${m}`)); console.log(`Synchronous invocation of addT returned ${addT(1,2,3,4)}`);

尝试使用jThread。https://github.com/cheprasov/jThread

// You can use simple calling like this
jThread(
    function(arr){
        //... some code for Worker
        return arr;
    }
    ,function(arr){
        //... done code
    }
)( [1,2,3,4,5,6,7] ); // some params

我使用这样的代码,你可以将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; }

将Adria的响应放在一个可复制粘贴的函数中,该函数适用于当前的Chrome和FF,但不适用于IE10 (worker from blob会导致安全错误)。

var newWorker = function (funcObj) {
    // Build a worker from an anonymous function body
    var blobURL = URL.createObjectURL(new Blob(
        ['(', funcObj.toString(), ')()'],
        {type: 'application/javascript'}
     ));

    var worker = new Worker(blobURL);

    // Won't be needing this anymore
    URL.revokeObjectURL(blobURL);

    return worker;
}

下面是一个工作示例http://jsfiddle.net/ubershmekel/YYzvr/