Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Cache Static Assets with Service Workers using sw-precache


    A service worker is a script that runs in the background without access to the UI, and a requisite for a Progressive Web App. They can be used, among others, for caching requests and assets.

    Creating a Service Worker is not easy, and can be repetitive to do it for every single app. That’s where sw-precache jumps in, a module for automating the creation of service workers in a declarative way.

    This lesson will go through creating a Service Worker using sw-precache.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: First, we need to install sw-precache. Open a console and type npm install sw-precache. Let's save it globally.

    Then we need to create a configuration file for sw. Let's call it swConfig.js. Then type module.supports, and here is where we can define the configuration for the service worker precache plug-in.

    At least what we need is to define the files that will be cached by the service worker. For that, write staticFileGlobs, which is an array of paths.

    At least we need to cache the index html, then manifest.json, and all the Java scripts which are in this folder. We can use global paths to define multiple files. Let's save it.

    Then we need to run sw-precache--config, and then the path to the config file. This will generate our service worker file. Understanding a service worker in detail is out of the scope of this course, because it can take a course of its own, but at least, let's just skim it over.

    The service worker adds a hash to the files that we define. Then it has a bunch of utility functions.

    The most important thing is that it has three events. Install, which, as you can guess, is called when the service worker gets installed. What it does is to cache all the files that we define.

    Then we have the activate event. This is called when the service worker gets updated and there is a new version. This event will remove all the entries from the cache, so in the next install event, the new files get updated.

    Finally, we have the fetch event. Since this service worker uses a cache-first strategy, that means that if a file is found in the cache, it will be loaded. If not, it will load it from the URL.

    That happens down here. It opens it from the cache. If not, it will perform the fetch request.