Successful service worker solution with sw-precache

I’ve asked many questions here, so time to give a little back. I’ve just very quickly and successfully got service worker to work for my Github Pages deployed Hugo site using sw-precache, so here’s a quick tutorial.

First install sw-precache:

npm i sw-precache --save-dev

Of course, I want Hugo to build to my master branch’s /docs folder because that’s where my Github Pages site should be set to serve from. In which case, I need to change a setting in config.toml:

publishDir = "docs"

(This will mean hugo builds create a /docs folder rather than /public.)

Next, I need to place the service worker registration script in my /static/js folder and link to it just on my homepage. In my case, this meant using an if block in baseof.html:

{{ if .Page.IsHome }}
    <script src="{{ .Site.BaseURL }}js/service-worker-registration.js"></script>
{{ end }}

Actually generating the service worker can be done using sw-precache's CLI, as part of the build script. In the following, I run hugo, then run sw-precache with the docs subfolder arg.

"build": "hugo && sw-precache --root=docs"

This places a service-worker.js file in the root of /docs with all files in /docs listed for caching.

After a push to the master branch, that’s it! Note that each file reference is cachebusted in service-worker.js, so that a new service worker is registered automatically when you push changes.

For extra points, you should have a manifest.json file in the root (/static folder) as well.

4 Likes

Great tip, but one in return:

The most portable way to create the URL above is:

    <script src="{{ "js/service-worker-registration.js" | absURL }}"></script>```
1 Like

Ah, thanks. Actually, I’m trying to find a way to package up my Hugo site so that it can work locally (just off the file system). Currently, the pathing is all wrong. I guess this may help.