Search code examples
javascriptservice-workersw-precache

CDN Service Worker


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


Solution

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