Using sw-precache with client-side URL routes for a single page app

房东的猫 提交于 2019-12-03 16:16:10

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
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!