Instructor: To use web workers, we're going to need an index.html file. In here, we're going to need a script tag with the source pointing to main.js. Then let's go ahead and make main.js. Then we'll console.log in main. Let's save that.
We need to pull up this index.html in here, but it needs to be running on a server. I'm going to open up my terminal. We'll run npx serve. That will start up a server on my local network. I can go to localhost:5000. If I open up my console I'm going to see in main, perfect.
To get a file on a web worker, I'm going to create a worker object with new worker. We'll call this worker.js. This is just a path to a file that the browser can go and request. I'm going to copy that. We'll make a new file with that name. I'll console.log in worker. Save that. Go back to my main and save that, and we'll refresh. We'll see in main and in worker.
If I look at my sources here, then that's going to show me my threads. I have my main thread, my worker thread, and I can interact with those threads independently. I can also open up the worker.js file here and the main.js file here.
I'll also have these interact with each other. If I want to send a message to the worker -- maybe some data or something -- then I can say worker.postMessage("Hello, worker"). Then in the worker, I can accept that message by saying this.onmessage.
That's going to take an event, and then I can console.log('Worker received message'). I can say e -- that's our event -- .data and save that. We'll refresh here and now I can see worker received a message, "Hello, worker."
I can send a message back. I can say this.postMessage("Hello, main"). Go back to my main file here and say worker.onmessage, so when I receive a message from the worker, I'm going to get the event.
I can console.log('Main received message') and say e.data. Save that, refresh, and here we get, we're in our main, we're in our worker. The worker receives a message, "Hello, worker," and main receives a message, "Hello, main."
If I want to add a debugger in here, then I just add that there, refresh, and there I am, working in my debugger. I can also work in my worker. I refresh, and there I am in my worker file, using the regular debugger that I'm used to.
In review, all that you need to do to make all of this magic happen is, you need to have an index file, you need to have that index file served using a local server during development, so that the browser will request to the Web Worker. Then, you have a main file, which is going to construct the Web Worker, and point to a worker file which will be loaded.
Then, you can communicate between those two with onmessage and postMessage on the worker, using this. On the main side, you call postMessage on the worker, and you'd add an onmessage handler to the worker.