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.
To illustrate the problem, we use a simple example consisting of a page (index.html) with a button on it.
The Problem Code
The problem code is particularly simple.
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 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.