0

So I was wondering if there is any clever hack to make a function run with web workers instead a feeding it a separate file. Maybe like this :

let cpuIntensiveTask = ()=>{ //function body } runWithWorker(cpuIntensiveTask);

Instead of this

let worker = new Worker("file.js");

Shiva Teja
  • 417
  • 4
  • 16
  • You need the [Blob API](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and [`URL.createObjectURL`](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) for this. – Sebastian Simon Nov 22 '17 at 14:25

1 Answers1

0

You can inline a web worker as a blob without using a separate file:

<script id="worker1" type="javascript/worker">
  // This script won't be parsed by JS engines because its type is javascript/worker. 
  self.onmessage = function(e){
    self.postMessage('msg from worker');
  };
  // Rest of your worker code goes here.
</script>
<script>
  var blob = new Blob([ document.querySelector('#worker1').textContent ], { type: "text/javascript" });
  var worker = new Worker(window.URL.createObjectURL(blob));
  worker.onmessage = function(e) {
    console.log("Received: " + e.data);
  }
  worker.postMessage("hello");
  // Start the worker
</script>

Note that browser support might not be as robust with this method.

See here for additional details: https://stackoverflow.com/a/6454685/5535081

Donny West
  • 710
  • 3
  • 6