9504 shaares
222 private links
222 private links
How to create a web worker?
- Create a script that imports another one with
const worker = new Worker('worker.js'
- Bind events emitted by the worker with
worker.onmessage = function(event) { ... }
- Do the same in the web worker with
self.onmessage = function(event) { ... }
- Exchange messages with
worker.postMessage(payload)
orself.postMessage(payload)
One key difference between Web Workers and the main thread is that Web Workers have no access to the DOM or the UI. This means that they cannot directly manipulate the HTML elements on the page or interact with the user.