Search code examples
javascripthtmlweb-worker

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;

 }

Solution

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