DEV Community

Cover image for HTML Web Workers API 👩🏽‍💻ᝰ.
Himanay Khajuria
Himanay Khajuria

Posted on

2 1 1 1 1

HTML Web Workers API 👩🏽‍💻ᝰ.

HTML Web Workers API - Run JavaScript in Background!

Have you ever noticed that when a webpage runs a complex JavaScript
task, it sometimes lags or becomes unresponsive? 😟 That’s because
JavaScript normally runs on a single thread, meaning it can only do one
thing at a time.

But guess what? HTML Web Workers API is here to save the day! 🤩


🧐 What is a Web Worker?

A Web Worker is like a separate worker in a company. Imagine you run a bakery 🍞 and you are the only one baking, taking orders and handling customers. That would be exhausting, right? A Web Worker is like hiring an extra baker to handle the baking while you take care of orders.

Similarly, Web Workers help run JavaScript in the background, so the main page remains smooth and responsive! 🚀


🤷🏻‍♀️ Why Use Web Workers?

✅ Run heavy JavaScript code without freezing the page
✅ Improve user experience by keeping the UI responsive
✅ Perform calculations, data processing, and API requests smoothly


🛠 How to Create a Web Worker

Creating a Web Worker is easy! Let's see a step-by-step example. We will make a worker that counts numbers without blocking the main page. 🧮

Step 1️⃣: Create a JavaScript File for the Worker

Create a new file called worker.js and add this code:

self.onmessage = function (event) {
  let count = 0;
  for (let i = 0; i < event.data; i++) {
    count += i;
  }
  postMessage(count); // Send result back
};
Enter fullscreen mode Exit fullscreen mode

📌 Explanation:

  • self.onmessage listens for messages sent from the main script.
  • A loop runs and counts numbers up to a given value.
  • postMessage(count) sends the result back to the main script.

Step 2️⃣: Use the Worker in Your Main Script

Now, create an index.html and link it to a JavaScript file (script.js). Inside script.js, write this code:

const worker = new Worker("worker.js");

worker.onmessage = function (event) {
  console.log("Total Count:", event.data);
};

worker.postMessage(1000000); // Send number to worker
Enter fullscreen mode Exit fullscreen mode

📌 Explanation:

  • new Worker("worker.js") creates a worker.
  • worker.postMessage(1000000) sends data (a number) to the worker.
  • worker.onmessage receives the result from the worker.
  • Now, even if we calculate up to 1,000,000, the page won't freeze! 🏆

🔥 Real-World Use Cases

Web Workers are useful for:

  • 📊 Data Processing – Handling large JSON data
  • 🎮 Gaming – Running game logic without affecting UI
  • 🔍 Background API Requests – Fetching data without blocking the page

⚠️ Limitations of Web Workers

🚫 No DOM access (can't update HTML directly)
🚫 Can’t use alert() or console.log() in worker files
🚫 Can’t directly communicate with other workers


↪️ Conclusion

The Web Workers API is a powerful tool to keep web applications fast and smooth. If your website does heavy processing, offloading tasks to a Web Worker is a game-changer! 🥳

🖇️ Learning Resources

HTML Web Workers API

➥ Check out my Technical Presentation along with the slide notes for a better understanding 🎥: 🔗 View Presentation

💼 Let’s connect on LinkedIn! 👥💬

Your thoughts are welcome in the comments! 💬

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or leave a kind comment!

Okay