Simple Use Case for Service Workers

July 14, 2018 0 Comments

Simple Use Case for Service Workers



A simple example demonstrating using a service worker to pre-cache a JavaScript application.

Wrote this article while thinking of a solution to improve the user experience of a web page that dynamically loads a React application into an iFrame.

The Problem

To illustrate the problem, we use a simple example consisting of a page (index.html) with a button on it.

Pressing the button creates an iFrame that loads a second page (iframe.html) that in-turn loads a JavaScript application (script.js); imagine that this file is large (say a complex React application).

The good news is that we delay loading the large JavaScript file until we click the button. The bad news, is that once we click the button the browser has to download the file (slow) before running the JavaScript application in the iFrame.

The Problem Code

The problem code is particularly simple.




The Solution

The general idea is that we want to have the “large” file, script.js, cached asynchronously when the first page, index.html, loads. With this in place, when we click the button, script.js is served out of a cache (fast).

The key to this solution is using a service worker which are supported in all modern browsers (not IE11; this solution does not break IE11).

The Solution Code

We first add the service worker loader code to…


and create the service worker code…


The Solution in Action

First, to avoid confusion between the browser and service worker caches, I disabled the browser cache by setting the server to expire the content immediately; using http-server.

npx http-server -c-1

Using the Network tab in Chrome Developer Tools, we can see that when index.html is initially loaded, worker.js is loaded asynchronously…

…and starts a service worker (as seen in the Application tab)

The service worker, in turn, loads script.js into a cache; see Network tab above and Application tab below.

When we then press the button, index.html gets iframe.html from the service worker (which in turn gets it from the web server); as seen in the Network tab.

On the other hand, index.html gets script.js from the service worker (which in turn gets it from the service worker cache); notice there is no second network entry for script.js at the bottom.

note: It is not entirely clear why worker.js is loaded a second time at the end.


While it took a bit of time to get my head around service workers, in the end, I found them to be a powerful way to do a number special things; in particular managing cached content.

Tag cloud