Web worker is a JS working in the background, without affecting the performance of the page.
new Worker(url)
A worker is an object created using a constructor (e.g., Worker()
) that runs a named JavaScript file — this file contains the code that will run in the worker thread.
w = new Worker("demo_workers.js"); // populates the HTML element with event data w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; w.terminate();
When executing long running JS in an HTML page, the page becomes unresponsive until the script is finished.
A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page.
const myWorker = new Worker(new URL("worker.js", import.meta.url));
you can run almost any code you like inside a worker thread. There are some exceptions: for example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the Window object.
Dedicated Worker
Shared workers
Service Worker