Yes, you read that title right. In most web applications there is an implicit assumption that network access will be available. Whether your site is server-side rendered, statically generated, or built entirely by the browser — HTML, CSS, and JS are fetched through HTTP requests over the network. As each page loads, it may fetch additional resources or communicate with third-party APIs. With a quick examination of the network tab you can see that sites are chatty. From Google Analytics events to Stripe widgets to bug tracking software, a single page may be accessing the network constantly without any user input. What if we challenge that basic assumption? How do we, as web developers, serve our users when the network isn’t available?
To help deal with this issue, Google, Samsung, Mozilla and other companies teamed up to introduce the first W3C draft of a service worker in May of 2014. But before we get to that, let’s examine a basic web worker — a JavaScript file that runs in the “background” of the main application. A web worker has its own thread but can still communicate with the main JavaScript thread. This separate thread allows it to perform tasks without blocking the execution of code in the main application which makes it perfect for performing computationally expensive tasks in the background without interrupting the user experience. Web workers run in a separate context from the current window and cannot access the DOM or the window object.
A service worker is a specialized web worker that acts like a proxy between your site and third parties — requests are intercepted by it and responses are routed through it. They are tied to an origin and path or pattern (of a URL) and respond to events (e.g. fetch) at that origin.
