我现在的问题是我有一个服务工作者使用名为service-worker.js
的旧代码我已经决定彻底删除该工作人员,而是切换到一个名为sw.js
的新工作
然而,当我实现service-worker.js
时,我忘记将我的nginx缓存设置为no-cache
,所以现在我遇到了一个旧的服务工作者,他们使用过时的代码而不是过时的代码即使我每天使用新代码运行部署,也会更新。 我家里有一台电脑,说它已经在这位老服务工作者身上运行了2周
我现在只是永远坚持这位老服务工作者吗?
我将SWPrecacheWebpackPlugin
与旧服务工作者一起使用,OfflinePlugin
用于新服务
这是旧的服务工作者代码
webpack.config
new SWPrecacheWebpackPlugin(
{
filename: 'service-worker.js',
minify: true,
navigateFallback: PUBLIC_PATH + 'index.html',
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/, /(icons)/],
}
),
src/registerServiceWorker.js
export default function register () { // Register the service worker
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
window.addEventListener('load', () => {
const swUrl = '/service-worker.js';
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
});
}
}
export function unregister () {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
以下是新服务工作者
webpack.prod.js
new OfflinePlugin({
autoUpdate: true,
ServiceWorker: {
events: true
}
})
index.js
OfflinePluginRuntime.install({
onUpdating: () => {
console.log('SW Event:', 'onUpdating');
},
onUpdateReady: () => {
console.log('SW Event:', 'onUpdateReady');
// Tells to new SW to take control immediately
OfflinePluginRuntime.applyUpdate();
},
onUpdated: () => {
console.log('SW Event:', 'onUpdated');
// Reload the webpage to load into the new version
window.location.reload();
},
onUpdateFailed: () => {
console.log('SW Event:', 'onUpdateFailed');
}
})