Return to site

Simple Service Worker for Caching

Caching assets offline and reducing network requests for VR sites

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).

Quick Start

  1. Grab the Service Worker Template. Save it as serviceworker.js next to your index.html file.
  2. For files we want cache-then-network, add the paths or URLs to the cacheFirstFiles array.
  3. For files we want network-else-cache, add the paths or URLs to the networkFirstFiles array.
  4. Register the service worker with navigator.serviceWorker.register('serviceworker.js'); in your HTML or in one of your JavaScript files.

And that's it! If you want to know how the service worker works or want to tweak the caching strategies, read the rest of the template JavaScript file, and refer to Offline Cookbook or Service Worker Cookbook.

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!

    All Posts
    ×

    Almost done…

    We just sent you an email. Please click the link in the email to confirm your subscription!

    OKSubscriptions powered by Strikingly