如何将函数传递给JavaScript Web Worker [英] How to pass functions to JavaScript Web Worker
问题描述
我想通过 postMessage()
将函数(或函数)传递给Web worker,因为我无法引用常规文件。
I would like to pass a function (or functions) via a postMessage()
to a web worker, because I can't refer to regular files.
要关闭Web工作者,我将对象URL(从Blob创建)传递给 Worker
构造函数。然后我传递了一条消息,但到目前为止没有运气在消息中添加功能。
To kick the web worker off, I am passing an object URL (created from a Blob) to the Worker
constructor. Then I am passing a message, but so far no luck putting a function in the message.
(JSON)消息不能直接包含函数(按照规定这里),虽然理论上允许使用importScripts,但到目前为止我还没有在Chrome或Firefox中使用过它。
The (JSON) message cannot contain functions directly (as stipulated here), and although importScripts is theoretically allowed, I have not had any success using it so far in Chrome or Firefox.
html文件的正文:
The body of the html file:
<div id="divText">1234</div>
<script>
var greeter = function greet(name) {
return "hello " + name;
};
function webWorkerWorker() {
self.postMessage("started1");
self.onmessage = function(event) {
importScripts(event.data.content);
self.postMessage("importScripts success");
var result = greeter("john");
self.postMessage(result);
};
}
var functionBody = mylib.extractFunctionBody(webWorkerWorker);
var functionBlob = mylib.createBlob([functionBody]);
var functionUrl = mylib.createObjectURL(functionBlob);
var functionBody2 = mylib.extractFunctionBody(greeter);
var functionBlob2 = mylib.createBlob([greeter]);
var functionUrl2 = mylib.createObjectURL(functionBlob2);
var worker = new Worker(functionUrl);
worker.onmessage = function(event) {
document.getElementById("divText").innerHTML = event.data;
}
worker.postMessage({
type: "init",
content: functionUrl2
});
</script>
目前,它会将divText值设置为importScripts success。
Currently it results in setting the divText value to "importScripts success".
我做错了什么?还有另一种方法可以将函数传递给Web worker吗?或者它是不可能的?
Am I doing something wrong? Is there another way that functions can be passed to web workers? Or is it not possible?
推荐答案
原来这个方法工作正常,我的工人只有一个错误:
Turns out this method works fine, there was merely a bug in my worker:
var result = greeter("john");
应该是
var result = greet("john");
这是有道理的 - 我将绿色变量传递给工人,但没有理由这样做知道我传递的对象的变量名。
which makes sense - I'm passing the greeter variable to the worker, but there's no reason for it to know the variable name of the object I'm passing.
这篇关于如何将函数传递给JavaScript Web Worker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!