Web Worker

  • It enables you to write code that will be executed in its own thread on the processor separate from the browser thread.
  • Web Workers can exchange messages with the main process, but they have their own variables, and their own event loop.
  • Since web workers are in external files, they do not have access to the following JavaScript objects:
    • The window object
    • The document object
    • The parent object
  • Web Workers do not have access to DOM, so they are useful, mainly, for calculations, to use multiple CPU cores simultaneously and are not meant to perform UI operations.
  • Types of Web Worker:
    • Dedicated Workers - These are workers that are utilized by a single script.
    • Shared Workers - These are workers that are utilized by multiple scripts running in different windows, IFrames, etc.
    • Service Workers - These act as proxy servers between web applications, the browser, and the network. Mostly used for push notifications and sync APIs.

Creating a Web Worker

const worker = new Worker(path_to_script); // Dedicated Worker
const sharedWorker = new SharedWorker(path_to_script); // Shared Worker

Service Worker

  • It’s a technology that allows your web application to use cached resources first, and provide default experience offline, before getting more data from the network later. This principle is commonly known as Offline First.
  • Service Workers actively use promises.
  • A Service Worker has to be installed, activated and then it can react on fetch, push and sync events.
  • Can be used to implement push notifications API?? maybe in react??
  • Maybe useful in PWA and offline Apps??