我正在使用带有Angular-cli-1.6.0的workbox-build-2.1.2和workbox-sw-2.1.2,一切正常,但是当我更新App并为生产和sw.js构建它时文件被修改然后在Chrome浏览器中服务工作者没有更新它继续使用旧版本,直到我手动取消注册它。如果它没有安装新的sw.js文件,并且在安装新版本时它还会清理旧网站的旧数据并自动启动新的平板,还是需要设置该部分?。
以下是我在Angulars主文件中注册sw.js的方法:
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(registerServiceWorker)
.catch(err => console.log(err));
function registerServiceWorker() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('sw.js')
.then(reg => {
log('Registration successful', reg);
reg.onupdatefound = () => {
const installingWorker = reg.installing;
installingWorker.onstatechange = () => {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
log('New or updated content is available', installingWorker);
} else {
log('Content is now available offline', installingWorker);
}
break;
case 'redundant':
console.error('The installing service worker became redundant', installingWorker);
break;
default:
log(installingWorker.state);
break;
}
};
};
})
.catch(e => {
console.error('Error during service worker registration:', e);
});
} else {
console.warn('Service Worker is not supported');
}
}
我使用npm
运行的generate-sw文件const workboxBuild = require('workbox-build');
const SRC_DIR = 'src';
const BUILD_DIR = 'public';
const SW = 'sw.js';
const globPatterns = [
"**/*.{ico,html,css,js,woff,json}"
];
const globIgnores = [
"sw.js"
];
const input = {
swSrc: `${SRC_DIR}/${SW}`,
swDest: `${BUILD_DIR}/${SW}`,
globDirectory: BUILD_DIR,
globPatterns: globPatterns,
globIgnores: globIgnores,
maximumFileSizeToCacheInBytes: 4000000
};
workboxBuild.injectManifest(input).then(() => {
console.log(`The service worker ${BUILD_DIR}/${SW} has been injected`);
});
和基础sw.js文件
importScripts('workbox-sw.prod.v2.1.2.js');
const workboxSW = new self.WorkboxSW({clientsClaim: true});
workboxSW.precache([]);
workboxSW.router.registerNavigationRoute('/index.html');
*****更新*****
将express.js用于开发服务器我将Cache-Control设置为零,现在当我重新加载页面时,服务工作者会更新到更新的版本。在生产中混淆了Cache-Control设置为天/年,服务工作者需要多长时间才能更新,并且它会清除旧现金和indexDB,还是我们必须手动执行
这是express的代码:
app.use('/', express.static(publicFolderPath, {maxAge: 0}));
app.get('*', (req, res) => {
res.sendFile('index.html');
});
答案 0 :(得分:3)
例如:
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
请参阅此链接:https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker
希望这有帮助