每次我使用Angular项目对index.html进行任何更改时,Service Worker都不会得到更新,并且总是在index.html上提供旧的缓存版本。我该如何解决这个问题(同时,在服务器端和浏览器端也没有缓存)
这是我的ngsw-config文件:
{
"index": "/index.html",
"assetGroups": [{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.json"
],
"versionedFiles": [
"/*.bundle.css",
"/*.bundle.js",
"/*.chunk.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
}]
}我的请求响应头部:

你知道怎么解决这个问题吗?
谢谢
发布于 2018-06-08 13:24:16
我认为问题出在ngsw-config中。versionedFiles下的.css和.js条目可能与dist文件夹中的.css和.js文件不匹配,如果它们的名称中没有.bundle或.chunk。在较新版本的Angular中,这些条目被替换为"/*.js"和"/*.css",并且dist文件夹中的文件在为生产构建时没有.bundle或.chunk。
因此,问题实际上是.js和.css文件没有被缓存,每当服务器上的文件被更新时,应用程序就不再找到它们,浏览器在服务工作者加载“缓存”的文件、检测更改和更新文件之前抛出错误(因为它返回index.html)。
在Angular 6中,versionedFiles的行为与files相同,已被弃用。因此,您的ngsw-config.json应该如下所示:
{
"index": "/index.html",
"assetGroups": [{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.json",
"/*.css",
"/*.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
}]
}发布于 2018-12-14 00:55:16
您可以在service worker中使用如下代码强制service worker删除所有以前的SW缓存(也包括index.html):
const DIRTY_CACHE = 'application-version-number-or-whatever';
self.addEventListener('install', () => {
// Skip over the "waiting" lifecycle state, to ensure that our
// new service worker is activated immediately, even if there's
// another tab open controlled by our older service worker code.
self.skipWaiting();
});
self.addEventListener('activate', event => {
self.registration.unregister();
event.waitUntil(
caches
.keys()
.then(cacheNames =>
cacheNames.filter(cacheName => cacheName.indexOf(DIRTY_CACHE) !== -1),
)
.then(cachesToDelete =>
Promise.all(
cachesToDelete.map(cacheToDelete => caches.delete(cacheToDelete)),
),
)
.then(() => self.clients.claim()),
);
});更详细的解释可以在in this article中找到
也许不是最好的策略,但解决了这个问题,可能是因为有一个糟糕的expires头。
https://stackoverflow.com/questions/49142968
复制相似问题