I am making a web worker in JavaScript in order to process two functions at the same time and I have checked several different answers on Stack Overflow and I found all of them use <script type="worker-script"> to define another function we want to process at the same time.
However, for me, on my programming tool (I use Sublime Text), the syntax highlighter doesn't parse it and just leaves it as white text. If it is the code, it will give different colors based on different types.
Example:
<!DOCTYPE html>
<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" })
// Note: window.webkitURL.createObjectURL() in Chrome 10+.
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
console.log("Received: " + e.data);
}
worker.postMessage("hello"); // Start the worker.
</script>
Could someone explain to me why this doesn't work and give me better solutions?
From: Web workers without a separate Javascript file?
Updated:
I just checked another question related to my question: How to run two operations at the same time using either web worker or event loop in javascript
I think if you need to use web worker, then you have to select the content of a script, but I really have no idea of that.
It doesn't get Javascript highlighting because you TOLD the editor that the snippet was not Javascript. That's what the type attribute is for -- it defines the language being used. MAYBE you can configure your editor to tell it that "worker-script" is like "Javascript".