Loading...

HTML Web Workers

Long JavaScript loops can freeze buttons and scrolling. Web Workers move heavy work to a background thread.

Direct answer

Create new Worker("worker.js"), then postMessage data to the worker and listen for message events back. Workers cannot touch the DOM directly — they compute and return results. Serve files over http(s) for reliable worker loading.

Worker pattern (page side)

html
HTML Code
<script>
const w = new Worker("worker.js");
w.postMessage(40);
w.onmessage = (e) => console.log("result", e.data);
</script>

worker.js would listen for onmessage, compute, and postMessage a result. Exact worker file contents are a JavaScript topic — here you learn why HTML pages use them.

Try it

  1. Read an introductory worker example from a trusted docs site
  2. Note that DOM updates stay on the main page script
  3. Think of one heavy task (large JSON filter) that could move to a worker
  4. Remember this is optional advanced material

Easy mistakes

  • Expecting workers to call document.querySelector directly
  • Loading workers from incompatible origins or odd file paths
  • Using workers for tiny tasks that do not need them

Summary

  • Workers run JS off the UI thread
  • Communicate with messages
  • No direct DOM access from workers
  • Use for heavy computation

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
3
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top