Search code examples
web-workerservice-worker

Service worker inside Web Workers


What would be the correct way to implement a webworker that can use a service worker to handle network calls. For example

  • I have an index.html file with its own logic for rendering data
  • Then this web worker is responsible for sending the data that needs to be rendered and triggering the render process
  • The webworker will use the service worker for fetching and caching the network requests/json data.

Solution

  • The web worker and the service worker are effectively independent.

    If you have a service worker controlling a specific page, then any HTTP requests that originate from that page or from a web worker used on that page will trigger a fetch event on that service worker. This applies to HTTP requests triggered by either fetch() or XMLHttpRequest from the web worker. The web worker doesn't need to "know" about the service worker in advance or anything.

    Note that a service worker can send and respond to message events just like a web worker can, so you might be able to get away with eliminating the web worker entirely and moving all your logic to the service worker. But that depends on what exactly your web worker was doing, and what level of support you want for browsers that support web workers but don't (yet) support service workers.