Using sw-precache with client-side URL routes for

2019-03-29 23:15发布

How would one configure sw-precache to serve index.html for multiple dynamic routes?

This is for an Angular app that has index.html as the entry point. The current setup allows the app to be accessable offline only through /. So if a user go to /articles/list/popular as an entry point while offline they won't be able to browse it and would be given you're offline message. (although when online they'd be served the same index.html file on all requests as an entry point)

Can dynamicUrlToDependencies be used to do this? Or does this need to be handled by writing a separate SW script? Something like the following would do?

function serveIndexCacheFirst() {
  var request = new Request(INDEX_URL);
  return toolbox.cacheFirst(request);
}

toolbox.router.get(
   '(/articles/list/.+)|(/profiles/.+)(other-patterns)', 
    serveIndexCacheFirst);

2条回答
Lonely孤独者°
2楼-- · 2019-03-29 23:34

Yes, I think you can use dynamicUrlToDependencies, as mentioned in the documentation of the directoryIndex option: https://github.com/GoogleChrome/sw-precache#directoryindex-string.

查看更多
看我几分像从前
3楼-- · 2019-03-29 23:46

You can use sw-precache for this, without having to configure runtime caching via sw-toolbox or rolling your own solution.

The navigateFallback option allows you to specify a URL to be used as a "fallback" whenever you navigate to a URL that doesn't exist in the cache. It's the service worker equivalent to configuring a single entry point URL in your HTTP server, with a wildcard that routes all requests to that URL. This is obviously common with single-page apps.

There's also a navigateFallbackWhitelist option, which allows you to restrict the navigateFallback behavior to navigation requests that match one or more URL patterns. It's useful if you have a small set of known routes, and only want those to trigger the navigation fallback.

There's an example of those options in use as part of the app-shell-demo that's including with sw-precache.

In your specific setup, you might want:

{
  navigateFallback: '/index.html',
  // If you know that all valid client-side routes will begin with /articles
  navigateFallbackWhitelist: [/^\/articles/],
  // Additional options
}
查看更多
登录 后发表回答