Create-react-app 附带一个 registerServiceWorker.js 文件,其中包含注册服务工作人员的代码。我只是有点困惑它是如何工作的。有问题的代码是:
function registerValidSW(swUrl) {
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);
});
}
第一个控制台日志(显示“新内容可用;请刷新”)需要发生什么才能显示?
更具体地说,当 index.html 更改时(如果脚本文件名更改),如何触发此代码运行。
最佳答案
让我们一步步分解。
navigator.serviceWorker.register
当有效的 Service Worker 存在已建立时,Promise 就会被解析registration.onupdatefound
注册一个事件监听器,当 Service Worker 的 HTTP 请求已解析为之前的某个其他文件时(或者首次找到 SW 时)会触发该事件)registration.installing.onstatechange
为新 Service Worker 的生命周期更改(从安装到已安装、从已安装到激活等)注册监听器if (installingWorker.state === 'installed')
过滤掉除installed
之外的所有状态 - 因此其正分支将在每个新的 SW 之后执行已安装if (navigator.serviceWorker.controller)
检查页面当前是否由任何(以前的)Service Worker 控制。如果为 true,那么我们将在此处处理上述更新场景。
总结一下 - 这个 console.log
将在更新的(不是第一个)Service Worker 正确安装后执行。
index.html
更改后不会触发。仅检查 Service Worker 代码(由 serviceWorker.register
方法指向)。另请注意,通常浏览器(或至少是 Chrome?)在下载当前版本后 24 小时内不会检查新的软件版本。另请注意,如果 Service Worker 文件使用过于激进的缓存 header 发送,则为 Service Worker 文件设置的普通旧式 HTTP 缓存可能会出现困惑。
关于javascript - 究竟是什么触发了该 Service Worker 代码的运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47943267/