[英]Could worker.postmessage and worker.onmessage be called from inside different java script files, to use one worker.js?
I am new in Java script, and have recently learned about Web Workers, which are basically the solution to multi-threading in Java Script. 我是Java脚本的新手,并且最近了解了Web Workers,它们基本上是Java Script中多线程的解决方案。 In all the examples I found, they used both posting a message and receiving the response message from a web worker file in the same js file.
在我发现的所有示例中,他们都使用了发布消息和从同一js文件中的Web Worker文件接收响应消息的方式。 My question is, could I start the execution of a web worker inside one java script file and then receive the result of it on another location in a separate java script file like the example below:
我的问题是,我可以在一个Java脚本文件中开始执行Web Worker,然后在单独的Java脚本文件中的另一个位置接收它的结果,如下例所示:
//start.js
function startWebWorker()
{
var message = "execute";
var myWorker = new Worker("worker.js");
myWorker.postMessage(message);
}
//worker.js
this.onmessage = function(e)
{
if (e.data == "execute")
var result ;
result = doSomething();
this.postMessage(result);
}
//receive.js
function processResult(){
var myWorker = new Worker("worker.js");
myWorker.onmessage = function(e)
document.setElementById("myresult") = e.result;
}
You could assign the worker to a global variable and access it from any script 您可以将工作程序分配给全局变量,然后从任何脚本访问它
window.myWorker = new Worker('worker.js')
Which you would access in some other script with 您将使用其他脚本访问的内容
window.myWorker.postMessage('hi there')
Or, even better, you could define the worker in a module 或者,甚至更好的是,您可以在模块中定义工作程序
export const worker = new Worker('worker.js')
and in modules, import it 并在模块中导入
<script type="module">
import { worker } from './worker-module.js'
worker.postMessage('hi there')
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.