94

如何使用从字符串(通过 POST 请求提供)创建 Web 工作者?

我能想到的一种方法,但我不确定如何实现它,是通过从服务器响应创建一个 data-URI,并将其传递给 Worker 构造函数,但我听说有些浏览器不允许这是因为相同的原产地政策。

MDN 声明了有关数据 URI 的原始策略的不确定性

注意:作为 Worker 构造函数参数传递的 URI 必须遵守同源策略。目前,浏览器供应商对于数据 URI 是否同源存在分歧;Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0) 及更高版本允许数据 URI 作为工作人员的有效脚本。其他浏览器可能不同意。

这里还有一篇在 whatwg 上讨论它的帖子

4

10 回答 10

158

概括

  • blob:适用于 Chrome 8+、Firefox 6+、Safari 6.0+、Opera 15+
  • data:application/javascript歌剧 10.60 - 12
  • eval否则(IE 10+)

URL.createObjectURL(<Blob blob>)可用于从字符串创建 Web 工作者。可以使用已弃用BlobBuilder的API或构造函数来创建 blob 。Blob

演示:http: //jsfiddle.net/uqcFM/49/

// URL.createObjectURL
window.URL = window.URL || window.webkitURL;

// "Server response", used in all examples
var response = "self.onmessage=function(e){postMessage('Worker: '+e.data);}";

var blob;
try {
    blob = new Blob([response], {type: 'application/javascript'});
} catch (e) { // Backwards-compatibility
    window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
    blob = new BlobBuilder();
    blob.append(response);
    blob = blob.getBlob();
}
var worker = new Worker(URL.createObjectURL(blob));

// Test, used in all examples:
worker.onmessage = function(e) {
    alert('Response: ' + e.data);
};
worker.postMessage('Test');

兼容性

以下浏览器源代码支持 Web Worker :

  • 铬 3
  • 火狐 3.5
  • IE 10
  • 歌剧 10.60
  • 野生动物园 4

这个方法的支持是基于BlobAPI和URL.createObjectUrl方法的支持。Blob兼容性

  • Chrome 8+ ( WebKitBlobBuilder), 20+ (Blob构造函数)
  • Firefox 6+ ( MozBlobBuilder), 13+ (Blob构造函数)
  • Safari 6+(Blob构造函数)

IE10 支持MSBlobBuilderURL.createObjectURL. 但是,尝试从blob:-URL 创建 Web Worker 会引发 SecurityError。

Opera 12 不支持URLAPI。URL由于. _ _browser.js

后备 1:数据 URI

Opera 支持 data-URIs 作为Worker构造函数的参数。注意:不要忘记转义特殊字符(例如#%)。

// response as defined in the first example
var worker = new Worker('data:application/javascript,' +
                        encodeURIComponent(response) );
// ... Test as defined in the first example

演示:http: //jsfiddle.net/uqcFM/37/

后备 2:评估

eval可用作 Safari (<6) 和 IE 10 的后备。

// Worker-helper.js
self.onmessage = function(e) {
    self.onmessage = null; // Clean-up
    eval(e.data);
};
// Usage:
var worker = new Worker('Worker-helper.js');
// `response` as defined in the first example
worker.postMessage(response);
// .. Test as defined in the first example
于 2012-04-29T12:53:13.127 回答
16

我同意当前接受的答案,但通常编辑和管理工作人员代码会很忙,因为它是以字符串的形式出现的。

因此,我们可以选择使用下面的方法,我们可以将 worker 保留为函数,然后转换为 string->blob:

// function to be your worker
function workerFunction() {
    var self = this;
    self.onmessage = function(e) {
        console.log('Received input: ', e.data); // message received from main thread
        self.postMessage("Response back to main thread");
    }
}


///////////////////////////////

var dataObj = '(' + workerFunction + ')();'; // here is the trick to convert the above fucntion to string
var blob = new Blob([dataObj.replace('"use strict";', '')]); // firefox adds "use strict"; to any function which might block worker execution so knock it off

var blobURL = (window.URL ? URL : webkitURL).createObjectURL(blob, {
    type: 'application/javascript; charset=utf-8'
});


var worker = new Worker(blobURL); // spawn new worker

worker.onmessage = function(e) {
    console.log('Worker said: ', e.data); // message received from worker
};
worker.postMessage("some input to worker"); // Send data to our worker.

这是在 IE11+ 和 FF 和 Chrome 中测试的

于 2016-05-11T07:36:33.217 回答
9

由于支持向后兼容性,接受的答案有点复杂,所以我想发布相同的内容但简化了。在您的(现代)浏览器控制台中尝试此操作:

const code = "console.log('Hello from web worker!')"
const blob = new Blob([code], {type: 'application/javascript'})
const worker = new Worker(URL.createObjectURL(blob))
// See the output in your console.

于 2020-05-05T19:20:05.973 回答
4

我已经根据您的大部分想法采取了一种方法,并添加了一些我的想法。我的代码在worker上唯一需要的是使用'this'来引用'self'范围。我很确定这是非常可改进的:

// Sample code
var code = function() {
    this.onmessage = function(e) {
        this.postMessage('Worker: '+e.data);
        this.postMessage('Worker2: '+e.data);
    };
};

// New thread worker code
FakeWorkerCode = function(code, worker) {
    code.call(this);
    this.worker = worker;
}
FakeWorkerCode.prototype.postMessage = function(e) {
    this.worker.onmessage({data: e});
}
// Main thread worker side
FakeWorker = function(code) {
    this.code = new FakeWorkerCode(code, this);
}
FakeWorker.prototype.postMessage = function(e) {
    this.code.onmessage({data: e});
}

// Utilities for generating workers
Utils = {
    stringifyFunction: function(func) {
        // Stringify the code
        return '(' + func + ').call(self);';
    },
    generateWorker: function(code) {
        // URL.createObjectURL
        windowURL = window.URL || window.webkitURL;   
        var blob, worker;
        var stringified = Utils.stringifyFunction(code);
        try {
            blob = new Blob([stringified], {type: 'application/javascript'});
        } catch (e) { // Backwards-compatibility
            window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
            blob = new BlobBuilder();
            blob.append(stringified);
            blob = blob.getBlob();
        }

        if ("Worker" in window) {
            worker = new Worker(windowURL.createObjectURL(blob));
        } else {
            worker = new FakeWorker(code);
        }
        return worker;
    }
};

// Generate worker
var worker = Utils.generateWorker(code);
// Test, used in all examples:
worker.onmessage = function(e) {
    alert('Response: ' + e.data);
};
function runWorker() {
    worker.postMessage('working fine');
}

演示:http: //jsfiddle.net/8N6aR/

于 2014-02-11T16:40:15.847 回答
2

很好的答案 - 我今天在尝试创建具有后备功能的 Web Workers 不可用时(即在主线程中运行工作脚本)时一直在解决类似的问题。由于此线程与该主题有关,我想我会在这里提供我的解决方案:

    <script type="javascript/worker">
        //WORKER FUNCTIONS
        self.onmessage = function(event) {
            postMessage('Hello, ' + event.data.name + '!');
        }
    </script>

    <script type="text/javascript">

        function inlineWorker(parts, params, callback) {

            var URL = (window.URL || window.webkitURL);

            if (!URL && window.Worker) {

                var worker = new window.Worker(URL.createObjectURL(new Blob([parts], { "type" : "text/javascript" })));

                worker.onmessage = function(event) {
                  callback(event.data);
                };

                worker.postMessage(params);

            } else {

                var postMessage = function(result) {
                  callback(result);
                };

                var self = {}; //'self' in scope of inlineWorker. 
                eval(parts); //Converts self.onmessage function string to function on self via nearest scope (previous line) - please email chrisgwgreen.site@gmail.com if this could be tidier.
                self.onmessage({ 
                    data: params 
                });
            }
        }

        inlineWorker(
            document.querySelector('[type="javascript/worker"]').textContent, 
            {
                name: 'Chaps!!'
            },
            function(result) {
                document.body.innerHTML = result;
            }
        );

    </script>
</body>

于 2013-06-18T23:15:34.940 回答
1

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

task.js用于让 CPU 密集型代码在所有内核(node.js 和 web)上运行的简化接口

一个例子是

// turn blocking pure function into a worker task
const functionFromPostRequest = task.wrap('function (exampleArgument) {}');

// run task on a autoscaling worker pool
functionFromPostRequest('exampleArgumentValue').then(result => {
    // do something with result
});
于 2016-10-29T05:44:07.547 回答
1

扩展@Chanu_Sukarno 的代码,您可以简单地将工作函数(或字符串)传递给该函数,它将在网络工作人员中执行:

async function doWorkerTask(workerFunction, input, buffers) {
  // Create worker
  let fnString = '(' + workerFunction.toString().replace('"use strict";', '') + ')();';
  let workerBlob = new Blob([fnString]);
  let workerBlobURL = window.URL.createObjectURL(workerBlob, { type: 'application/javascript; charset=utf-8' });
  let worker = new Worker(workerBlobURL);

  // Run worker
  return await new Promise(function(resolve, reject) {
    worker.onmessage = function(e) { resolve(e.data); };
    worker.postMessage(input, buffers);
  });
}

以下是如何使用它的示例:

function myTask() {
  self.onmessage = function(e) {
    // do stuff with `e.data`, then:
    self.postMessage("my response");
    self.close();
  }
}
let output = await doWorkerTask(myTask, input, inputBuffers);
// now you can do something with `output` (which will be equal to "my response")


nodejs中,doWorkerTask看起来像这样:

async function doWorkerTask(workerFunction, input, buffers) {
  let Worker = require('webworker-threads').Worker;
  let worker = new Worker(workerFunction);

  // Run worker
  return await new Promise(function(resolve, reject) {
    worker.onmessage = function(e) { resolve(e.data); };
    worker.postMessage(input, buffers);
  });
}
于 2017-03-19T11:24:50.913 回答
0

我的解决方案(可以很容易地“承诺”......)

   function makeWorker(workerFunction, cb) {
        // Create worker
        var tplFun = "onmessage = function(e){console.log(e);   var args = Array.prototype.slice.call(e.data); var res=___.apply(this,args);postMessage(res);}"
        var fnTxt = workerFunction.toString().replace('"use strict";', '');
        var final = tplFun.replace("___", fnTxt);
        let workerBlob = new Blob([final]);
        let workerBlobURL = window.URL.createObjectURL(workerBlob, { type: 'application/javascript; charset=utf-8' });
        let worker = new Worker(workerBlobURL);
        return function () {
            var args = Array.prototype.slice.call(arguments);
            console.log(args)
            worker.postMessage(args);
            worker.onmessage = function (e) {
                console.log(e.data);
                cb(e.data);
            }
        }
    }

    function myTask(a, b, c) {
        return a * b * c;
    }

    function onresult(e) {
        alert(e);
    }
    var fn = makeWorker(myTask, onresult)
    fn(1, 2, 3);

可以很好地使用“纯和慢”功能!

于 2022-02-18T15:10:18.937 回答
-1

您可以通过将 更改为或来从objectURL获取真实数据,而不仅仅是 blob 。responseType"text""arraybuffer"

这是to到back到or的来回转换text/javascriptblobobjectURLblobtext/javascript

如果您想知道,我正在使用它来生成没有外部文件的网络工作者,
您可以使用它来返回二进制内容,例如 YouTube 视频;)(来自 <video> 标签资源属性)

var blob = new Blob(['self.onmessage=function(e){postMessage(e)}'],{type: 'text/javascript'});   //->console: (object)   Blob {size: 42, type: "text/javascript", slice: function}

var obju = URL.createObjectURL(js_blob); //->console:  "blob:http%3A//stackoverflow.com/02e79c2b-025a-4293-be0f-f121dd57ccf7"

var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:http%3A//stackoverflow.com/02e79c2b-025a-4293-be0f-f121dd57ccf7', true);
xhr.responseType = 'text'; /* or "blob" */
xhr.onreadystatechange = function(){
  if(xhr.DONE !== xhr.readyState) return;

  console.log(xhr.response);
}
xhr.send();

/*
  responseType "blob" ->console: (object)   Blob {size: 42, type: "text/javascript", slice: function}
  responseType "text" ->console: (text)     'self.onmessage=function(e){postMessage(e)}'
*/
于 2015-03-24T00:18:37.080 回答
-1

使用我的小插件https://github.com/zevero/worker-create

var worker_url = Worker.create("self.postMessage('Example post from Worker');");
var worker = new Worker(worker_url);

但你也可以给它一个功能。

于 2015-10-18T12:00:50.307 回答