Today I Learned

Service Workers

April 02, 2019

Service Workers

Our digital signage system uses HTML5 to play dynamic ads meaning ads that use data or logic to change automatically. The challenges with HTML5 are:

  • You need a constant internet connection for content
  • Constantly downloading content can mean gigs worth of requests for a simple digital ad each month

To get around these challenge I needed to:

  1. Cache main content locally- This handles excessive network usage
  2. Change the main cached content on demand- Content may need to change every few minutes
  3. Cache a background image- This will be shown when

A Bit of History

Our original dynamic ad implementation used app cache for offline capabilities. However this was limited and app cache was depreciated several years ago. We also considered creating a custom solution but I’m a fan of using as much standardized tech as possible. So we turned to service workers.

In the Service of Service Workers

The first thing to know about service workers is they are a bit more complicated than good ole app cache. As with any new tech everything becomes a bit clearer after a few tutorials. I’d recommend the following articles to anyone trying to use service workers.

A Third Way

After a few hours of tutorials I realized that service workers were not designed for what I needed. Service workers either look for local cached content, grab content from the network, or check the network and then fall back to the local cache. I needed to use local cache even when the network was available but still be able to easily change cashed content without refreshing the browser and still have a fall back graphic available when the machine is offline. Ugh…

Dynamically Defined Page Elements

Eventually I came up with a process of dynamically defining page elements using JS to reference a separate JS file for the actual file names and locations. Using this method I’m able to update the service workers cache by simply changing the variable in globals.js. This is most definitely a niche case for service workers but if you have a similar need I created a git repo with sample scripts.

Ryan Kovalchick

Written by Ryan Kovalchick who lives and works in Allentown Pennsylvania creating, fixing and building.