Service Workers are scripts that run in the background, separate from a webpage. They enable features such as push notifications, background syncing, and low-level control over requests and caching. There has been buzz about progressive web apps, but I had trouble finding clear resources for caching with service workers. The best is The Offline Cookbook by Jake Archibald.
VR applications typically come with many assets. Loading times are magnified when the user is in the headset. Service workers are great to speed up subsequent visits. If everything is cached correctly, next the a user visits the VR site, the site will load much faster. Below is a quick guide for accomplishing two things:
- Cache-then-network: Defining a list of URLs to pull from the cache if it's been loaded before and update the cache in the background from the network. We use this for images and models and fonts, assets that are unlikely to change often.
- Network-else-cache: Defining a list of URLs to always pull from the network, but pull from cache if the request fails (e..g, we are offline). We use this for frequently updated files (JS, CSS, HTML).
- Grab the Service Worker Template. Save it as serviceworker.js next to your index.html file.
- For files we want cache-then-network, add the paths or URLs to the cacheFirstFiles array.
- For files we want network-else-cache, add the paths or URLs to the networkFirstFiles array.
Testing the Service Worker
To see if the service worker is caching, use the browser developer tools:
- In Chrome, go to the Application panel and see the Service Workers section on the left sidebar.
- In Firefox, go to the Storage panel and see under the Cache Storage section. Also see about:debugging to see if the service worker is registered correctly.
In the network panel, the browser developer tools will also tell us when a file is fetched from cache or from the network (or both, in case of background update for cache-then-network):
Have fun caching!