Service Workers explained DRAFT

— a primer on service workers

:construction: Please note: You're previewing a draft, subject to change...

I’ve been hearing a lot about service workers for a couple of years now, but hadn’t really figured out what the fuzz was about. To me the term “Service Worker” doesn’t really ring any bells in it self, so it’s been somewhat of an abstract concept to me. That is, until I read this short explanation:

Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.

Essentially meaning: Service Worker => Proxy

I don’t know if this makes just as much sense to you, but bear with me as we dig further into this:

The 1st time you visit a website (or a PWA) that registers a service worker not much happens: The service worker registers, installs - probably precaches some assets - and then sits idle waiting for any subsequent request(s).

The real McCoy is when you visit the same website (or PWA) the 2nd time - that is, after closing all browsers/tabs for the given site and re-opening it in a new tab/browser:
Note: In Service Worker mojo the ‘same’ website is called scope. This means you are visiting a page at the same level or deeper from where the SW was registered.

Now what happens is, the browser sees you’re visiting a page that is now controlled by your service worker and therefore it will proxy requests through your service worker (by raising a fetch event) for all the assets it needs to render the page (html, css, js, img) - and yes, also assets outside your current scope [CONFIRM!?].

If your service worker responds to the request through the event.respondWith(...) method then that asset will be used straight of the cache. If not, the browser will request the resource the usual way: From the browser’s own cache or from the server (your server or 3rd party).

Let’s visualize this:

Service Worker Request Flow