简体   繁体   中英

Cache internal routes with sw-precache

I'm creating a SPA using vanilla JavaScript and currently setting up sw-precache to handle the caching of resources. The service worker is generated as part of a gulp build and installed successfully. When I navigate to the root url ( http://127.0.0.1:8080/ ) whilst offline the app shell displays, illustrating that resources are indeed cached.

I'm now attempting to get the SW to handle internal routing without failing. When navigating to http://127.0.0.1:8080/dashboard_index whilst offline I get the message 'Site can't be reached'.

The app handles this routing on the client side via a series of event listeners on the users actions or, in the case of using the back button, the url. When accessing one of these urls, no calls to the server should be made. As such, the service worker should allow these links to 'fall through' to the client side code.

I've tried a few things and expected this Q/A to solve the problem. I've included the current state of the generate-service-worker gulp task, and with this setup I'd expect to be able to access /dashboard_index offine. Once this is working I can adapt the solution to cover other routes.

Any help much appreciated.

gulp.task('generate-service-worker', function(callback) {
  var  rootDir = './public';

  swPrecache.write(path.join(rootDir, 'sw.js'), {
    staticFileGlobs: [rootDir + '/*/*.{js,html,png,jpg,gif,svg}',
                      rootDir + '/*.{js,html,png,jpg,gif,json}'],
    stripPrefix: rootDir,
    navigateFallback: '/',
    navigateFallbackWhitelist: [/\/dashboard_index/],
    runtimeCaching: [{
      urlPattern: /^http:\/\/127\.0\.0\.1\:8080/getAllData, // Req returns all data the app needs
      handler: 'networkFirst'
    }],
    verbose: true
  }, callback);
});

update

The code to the application can be found here .

Removing the option navigateFallbackWhitelist does not chage the result.

Navigating to /dashboard_index whilst offline prints the following to the console.

The same An unknown error occurred when fetching the script. is also duplicated in the 'application > service workers' tab of chrome debug tools.

It's also noted that the runtimeCaching option is not caching the json response returned from that route.

For the record, in case anyone else runs into this, I believe this answer from the comments should address the issue:

Can you switch from navigateFallback: '/' to navigateFallback: '/index.html' ? You don't have an entry for '/' in your list of precached resources, but you do have an entry for '/index.html' . There's some logic in place to automatically treat '/' and '/index.html' as being equivalent, but that doesn't apply to what navigateFallback is doing...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM