1

I'm trying to set up a service worker using sw-precache to cache assets from CDNJS to be used offline. Unfortunately, this doesn't seem to be working. Here's what I have so far:

Before any of the scripts are loaded in index.html:

<script type='text/javascript'>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/js/service_worker.js')
      .then(function() {
        console.log("Service Worker Registered")
      })
  }
</script>

And here's the Gulp task I'm using to generate the service worker:

const config = require('../config')
const gulp = require('gulp')
const swPrecache = require('sw-precache')

gulp.task('serviceWorker', (callback) => {

  swPrecache.write(config.build.serviceWorker, {
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/cdnjs\.cloudflare\.com/,
        handler: 'networkFirst'
      }
    ]
  }, callback)
})

When I run the app, I see Service Worker Registered logged to the console. However, if I disconnect my wifi the app fails to loads the scripts. What am I doing wrong?

Errors

LandonSchropp
  • 10,084
  • 22
  • 86
  • 149

2 Answers2

5

You are registering service worker at some JS path /js/service_worker.js. Here scope constrains the service worker to only control the specified contents under that path /js/.

I suggest you to register service worker at root level i.e www.example.com/ then you are able to control all pages that being served under this domain.

Vivek Pratap Singh
  • 9,326
  • 5
  • 21
  • 34
0

I think your issue is with scoping.

Service worker only has a maximum scope of the directory it is in. That is to say, it can't load files/requests/responses that are pulled from a location at or above its structure, only below.

Therefore, if you change the location of your service worker to the root of your web project, the fetch event should fire and your assets should load from cache.

This is further explained here, in the "Register A service worker" section. https://developers.google.com/web/fundamentals/getting-started/primers/service-workers

Sakshi Nagpal
  • 1,003
  • 7
  • 16