What is a Service Worker?

November 16, 2018 · #web #pwa #javascript

If you read my first article talking about PWAs, you know I mentioned that a core pillar of PWAs is the ServiceWorker (SW)— but I didn’t quite explain what that was.

Service Worker

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction. — Google

Sounds cool right? Well it is! If you’re making a web app at MyApp.com the service worker will act as an event driven proxy which is given control over the network requests to or from MyApp.com.

Proxy diagram

The interface for defining behaviour is quite simple. You can write logic for your SW on any of the following events:

This primitive API is easily extensible into powerful libraries like WorkBox to abstract the developer from complex caching validation strategies and enable reliable app functionality even in poor network conditions.

Forecaast: Another Progressive Weather App

Forecaast demo

I made a demo app Forecaast; as you can see by the console log above I’m using the ‘install’ event to cache all the files needed to run the app offline.

Offline demo

As can be seen above, when chrome is switched offline, the application will still load like normal as the service worker responds with the cached assets.

Caveats

With great power comes great restrictions! While I highly suggest using service workers and building cool apps there are some prerequisites for them:

Thank you for making it here!

If you enjoyed this post, please consider sharing it or check out some of my other articles 🎉 Make sure to subscribe to my newsletter and follow me on Twitter/Github to see what I’m up to.