- [Instructor] Creating a dedicated worker is very simple. We need to create a separate file, it will be a JS file, and we shall call the worker constructor. So new Worker and the URL, very simple. Usually we want to save the return object that is a pointer to that worker if we want to send messages or terminate it later. Latest versions of some browsers also accepts a second argument that the other browser will just ignore with for example a name property.
It's an object with a name property. The name is useful for debugging purposes because when you have a lot of web workers that you have created and they are all threads working at the same time and you are doing console log messages or you are adding break points sometimes you don't know exactly which version of your thread and which worker are you currently running so now you can name them, so with the name property. Also, latest version of some browsers, this is a seat experimental, instead of creating a classic worker we can create an ES6 module worker and that module will also be able to import and export data from other modules as well and in that case when we set type as module we can also set credentials and what do we want to do with credentials when we are importing other modules inside.
So if you want to add event listener for example we can use self. This a good idea to reduce the usage of this because we know that this context might change, so self will never change within the context of a web worker. Typically, a dedicated worker is in a separate file, but sometimes we don't want that and we want to use code from our own file but run that code in a separated thread. To do that there is a hack, this is not really an API, it's a hack to make an inline or embedded web worker.
Then we create a URL based on that blob content and we create a worker with that URL. Another version of this is we can create a blob directly with a text inside and the final version is that we can create a function with all the code for our worker and then we take the string version of that code and we execute it, and that's basically the string that we are going to use as a blob, we are going to create the URL, and then a worker with it.
Just remember, creating embedded web workers or inline web workers is a hack and it might not work properly on some browsers, so you need to test on all your targeted browsers.
- Creating dedicated workers
- Creating shared workers
- Creating basic workers
- Sending messages to web workers
- Optimizing app performance with web workers
- Handling web worker errors