将sw-precache与单个页面应用程序的客户端URL路由一起使用 [英] Using sw-precache with client-side URL routes for a single page app
问题描述
如何将sw-precache配置为为多个动态路由提供index.html
?
How would one configure sw-precache to serve index.html
for multiple dynamic routes?
这是针对以index.html
作为入口点的Angular应用程序. 当前设置允许该应用可访问仅通过/
脱机.因此,如果用户在脱机时进入/articles/list/popular
作为切入点,则他们将无法浏览它,并且会向您显示脱机消息. (尽管在线时,它们将在所有请求上作为入口点提供相同的index.html
文件)
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)
可以使用 dynamicUrlToDependencies 吗?还是需要通过编写单独的SW脚本来处理?像下面这样会发生什么事?
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);
推荐答案
为此,您可以使用sw-precache
,而不必通过sw-toolbox
配置运行时缓存或使用自己的解决方案.
You can use sw-precache
for this, without having to configure runtime caching via sw-toolbox
or rolling your own solution.
navigateFallback
选项可让您指定要使用的URL当您导航到缓存中不存在的URL时,将其作为备用".服务工作人员等效于在HTTP服务器中配置单个入口点URL,并使用通配符将所有请求路由到该URL.这显然在单页面应用程序中很常见.
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.
还有一个 navigateFallbackWhitelist
选项,该选项可让您限制对与一个或多个URL模式匹配的导航请求的navigateFallback
行为.如果您只有一小部分已知路线,并且只希望这些路线触发导航后备导航,这将非常有用.
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.
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
}
这篇关于将sw-precache与单个页面应用程序的客户端URL路由一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!