简体   繁体   中英

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. 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. 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:

//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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM