HomeAbout

Workers

What is a Worker

Web worker is a JS working in the background, without affecting the performance of the page.

  • main thread (usually the UI) will run without being blocked/slowed down.
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();

Problem in details

When executing long running JS in an HTML page, the page becomes unresponsive until the script is finished.

  • Because JS is single threaded and browsers use a single event loop.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page.

  • You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
const myWorker = new Worker(new URL("worker.js", import.meta.url));

Limitations

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.

Worker Types

Dedicated Worker

  • workers that are utilized by a single script.
  • This context is represented by a DedicatedWorkerGlobalScope object.

Shared workers

  • utilized by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complex than dedicated workers — scripts must communicate via an active port.

Service Worker

  • They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.
AboutContact