Mrunay Uttarwar
Mrunay Uttarwar

@MrunayU

10 تغريدة Nov 07, 2022
🔷 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
You can read the unrolled version of this thread here: typefully.com

جاري تحميل الاقتراحات...