This content originally appeared on DEV Community and was authored by 101samovar
Video-tutorial: https://www.youtube.com/watch?v=VLIb-by_XUA
We need a new Worker object with the URL of the script file as a parameter.
To make the worker run we need to post a message to the worker.
To get data from the worker we use the onmessage method.
The data is in the data property of the event object.
In the worker script file we need to define the onmessage method.
The data from the main script is in the data property of the event object.
The web workers can’t be started for the local files.
So we need a web-server.
A NodeJs live-server will do.
script.js
const worker = new Worker('worker.js');
worker.postMessage('Hello!');
worker.onmessage = e => {
console.log(e.data);
}
worker.js
onmessage = e => {
console.log(e.data);
postMessage('Answer');
}
👋 See you next time. Have a nice day!
This content originally appeared on DEV Community and was authored by 101samovar

101samovar | Sciencx (2022-01-12T11:57:11+00:00) How to use web workers?. Retrieved from https://www.scien.cx/2022/01/12/how-to-use-web-workers/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.