0

I'm using sw-precache in a jekyll website to add offline capabilities with the following configuration:

gulp.task('generate-service-worker', function(cb) {
  var path = require('path');
  var swPrecache = require('sw-precache');
  var rootDir = '_site';
  var packageJson = require('./package.json');

  swPrecache.write('./service-worker.js', {
    staticFileGlobs: [rootDir + '/**/*.{html,css,png,jpg,gif,svg}', rootDir + '/js/*'],
    stripPrefix: rootDir + '/',
    runtimeCaching: [{
      urlPattern: /\/$/,
      handler: 'networkOnly'
    }],
    handleFetch: argv.cacheAssets || false,
    maximumFileSizeToCacheInBytes: 10485760, // 10 mb
    cacheId: packageJson.name + '-v' + packageJson.version
  }, cb);
});

The problem is that, when I change content in the website (for example, text in a blog post, or some text from the index page) the changes won't be shown until the new serviceworker version has been installed and the browser has been refreshed, which of course, is the expected behaviour of cacheFirst.

What I want is to make the request to the index of the site always network first, which is what I'm trying here:

runtimeCaching: [{
  urlPattern: /\/$/,
  handler: 'networkFirst'
}]

But this isn't working, the index is always getting fetch from the serviceworker and not from network, how can I accomplish this?

Carlos Martinez
  • 4,350
  • 5
  • 32
  • 62

3 Answers3

0

My problem is that I was including the actual page contents for precache: '/**/*.{html,css,png,jpg,gif,svg}'.

Excluding the html files works as expected:

'/**/*.{css,png,jpg,gif,svg}'
Carlos Martinez
  • 4,350
  • 5
  • 32
  • 62
0

Change the url pattern to

urlPattern: "'/'"

This is a exact match pattern. Your index will match to this and nothing else.

Ashrith
  • 655
  • 8
  • 20
0

The solution for this is, treat your index.html as dynamic content.

Change you sw webpack config to

new SWPrecacheWebpackPlugin({
  cacheId: 'yourcacheid',
  filename: 'service-worker.js',
  staticFileGlobs: [
    'dist/**/*.{js,css}'
  ],
  minify: true,
  stripPrefix: 'dist/',
  runtimeCaching: [{
    urlPattern: /\/$/,
    handler: 'networkFirst'
  }]
})

Remove your index.html from staticFileGlobs and add you root index to runtime caching.

Then look at your cache storage. You will see something like $$$toolbox-cache$$$https://your-domain.com as a new cache item. Inspect that and you can see your index cached there.

the_haystacker
  • 1,585
  • 18
  • 20