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

Already subscribed? Sign In


    Cache Static Assets with Service Workers using sw-precache

    Alex Jover MoralesAlex Jover Morales

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


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

    00:18 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.

    00:36 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.

    00:48 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.

    01:04 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.

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

    01:39 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.

    01:55 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.

    02:11 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.

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