我有以下情况:
我应该如何处理Web应用程序中API的更改?重要的是要考虑服务人员的生命周期。服务人员将继续使用以前的版本,直到重新加载Web,以便用户可能会使用过时的API端点或丢失新的必需参数。
当前,我正在做的是在安装新版本后立即重新加载页面,但是看来它无法完全正常工作,而且也不是很理想:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
console.log('Service worker registered')
setInterval(() => {
console.log('Checking for updates');
registration.update();
}, 1000 * 60 * 60); // Checking for updates every hour
if (!navigator.serviceWorker.controller) { // New user with no service worker
return;
}
var preventDevToolsReloadLoop;
navigator.serviceWorker.addEventListener('controllerchange', function (event) { // This event is called when a new sw is installed
if (preventDevToolsReloadLoop) return; // Ensure refresh is only called once. This works around a bug in "force update on reload" in chrome tools.
preventDevToolsReloadLoop = true;
console.log('Controller loaded');
window.location.reload();
});
});
} else {
console.log('Service worker not activated')
}
sw.js看起来像这样:
importScripts('/js/workbox.4c4f5ca6.js')
workbox.precaching.precacheAndRoute([ /*Routes...*/ ]);
workbox.clientsClaim()
workbox.skipWaiting()
workbox.routing.registerRoute(new RegExp('/js/.*'),
workbox.strategies.cacheFirst({}), 'GET')
workbox.routing.registerRoute(new RegExp('/.*'),
workbox.strategies.networkFirst({}), 'GET')