π· About HTML Web Workers API - 1
A Thread𧡠π
π What is a Web Worker?
β A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page.
β When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.
β You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
π Create a Web Worker File
β Now, let's create our web worker in an external JavaScript.
β Here, we create a script that counts.
β The script is stored in the "demo_workers.js" file.
β The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page.
β Note:- Normally web workers are not used for such simple scripts, but for more CPU intensive tasks.
π Create a Web Worker Object
β Now that we have the web worker file, we need to call it from an HTML page.
β The following lines checks if the worker already exists, if not - it creates a new web Worker object and runs the code in "demo_workers.JS".
β Then we can send and receive messages from the web worker.
β Add an "onmessage" event listener to the web worker.
β When the web worker posts a message, the code within the event listener is executed.
β The data from the web worker is stored in event.data.
Thanks for reading this thread β€οΈ
If you like it , make sure you:
π· Like the tweet
π· Retweet the first tweet β‘
For more content , follow:
@MrunayU