JS - sudo-arshia/tips_and_tricks GitHub Wiki

In JavaScript, there are three types of workers that can be used for multi-threading and background processing:

  1. Dedicated Workers: Dedicated workers are JavaScript files that run in the background on a separate thread. They are created using the Worker constructor. Dedicated workers have their own global scope and can perform time-consuming tasks without blocking the main thread. They communicate with the main thread using the postMessage() method and handle messages using the onmessage event.

Example:

// In the main thread
const worker = new Worker('worker.js');

worker.postMessage('Hello from the main thread!');

worker.onmessage = function(event) {
  console.log('Message received from worker:', event.data);
};

// In the worker.js file
self.onmessage = function(event) {
  console.log('Message received from main thread:', event.data);
  
  // Perform some processing
  
  self.postMessage('Hello from the worker!');
};
  1. Shared Workers: Shared workers are JavaScript files that can be accessed by multiple browsing contexts (e.g., tabs, iframes) within the same origin. They are created using the SharedWorker constructor. Shared workers have a shared global scope and can communicate with multiple clients using the postMessage() method and handle messages using the onconnect event.

Example:

// In the main thread
const worker = new SharedWorker('worker.js');

worker.port.addEventListener('message', function(event) {
  console.log('Message received from worker:', event.data);
});

worker.port.start();

worker.port.postMessage('Hello from the main thread!');

// In the worker.js file
self.addEventListener('connect', function(event) {
  const port = event.ports[0];

  port.addEventListener('message', function(event) {
    console.log('Message received from main thread:', event.data);

    // Perform some processing

    port.postMessage('Hello from the worker!');
  });

  port.start();
});
  1. Service Workers: Service workers are JavaScript files that act as network proxies between the web page and the network. They are designed to handle tasks such as caching, push notifications, and background synchronization. Service workers are registered using the navigator.serviceWorker.register() method and handle events such as fetch, push, and sync.

Example:

// In a service-worker.js file
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      if (response) {
        return response;
      }
      
      return fetch(event.request);
    })
  );
});

// In the main thread
navigator.serviceWorker.register('service-worker.js').then(function(registration) {
  console.log('Service Worker registered!');
});
Dedicated Workers Shared Workers Service Workers
Creation Created using the Worker constructor Created using the SharedWorker constructor Registered using the navigator.serviceWorker.register() method
Global Scope Has its own global scope Has a shared global scope Does not have a global scope
Thread Runs on a separate thread Runs on a separate thread Runs on a separate thread (specifically, a different context from the main thread)
Communication Communicates with the main thread using postMessage() and handles messages using the onmessage event Communicates with multiple clients using postMessage() and handles messages using the onconnect event Communicates with the web page using events such as fetch, push, and sync
Use Cases Background processing, heavy computations, and time-consuming tasks Communication and data sharing among multiple browsing contexts (e.g., tabs, iframes) Offline support, caching, push notifications, background synchronization, and other web platform features
Access to DOM Has access to the Worker global object, but not the DOM Does not have direct access to the DOM Limited access to the DOM (via the clients object or using the MessageChannel API)
Browser Support Widely supported in modern browsers Supported in modern browsers, but with some limitations Supported in modern browsers, but with limited support in older browsers (e.g., IE and some versions of Safari)

It's important to note that service workers are mainly used for offline support and other web platform features, rather than traditional multi-threading. They operate on a different thread and have a different purpose compared to dedicated and shared workers.