HomeToolsAbout a20k

Web Worker

What is it

Web Workers makes it possible to run a script operation in a background thread separate from the main execution thread of a web application.

  • allows the main (usually the UI) thread to run without being blocked/slowed down

You can run almost any code you like inside a worker thread.

Some exceptions:

  • can't directly manipulate the DOM from inside a worker
  • can't access certain methods from Window object
const myWorker = new Worker("/worker.js"); const first = document.querySelector("input#number1"); const second = document.querySelector("input#number2"); first.onchange = () => { myWorker.postMessage([first.value, second.value]); console.log("Message posted to worker"); };

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler

  • the message is contained within the message event's data property.
© VincentVanKoh