Javascript 到底是什么触发了此服务工作者代码的运行?
Create react应用程序附带一个registerServiceWorker.js文件,其中包含注册服务工作者的代码。我只是对它的工作原理有点困惑。有关守则是:Javascript 到底是什么触发了此服务工作者代码的运行?,javascript,service-worker,Javascript,Service Worker,Create react应用程序附带一个registerServiceWorker.js文件,其中包含注册服务工作者的代码。我只是对它的工作原理有点困惑。有关守则是: function registerValidSW(swUrl) { navigator.serviceWorker .register(swUrl) .then(registration => { registration.onupdatefound = () => {
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
Promise在建立有效的服务工作者存在时解析registration.onupdatefound
注册一个事件的侦听器,该事件是在Service Worker的HTTP请求已解析为以前以外的某个文件(或首次找到软件)时触发的registration.installing.onstatechange
为新服务人员的生命周期更改(从安装到安装,从安装到激活等)注册侦听器if(installingWorker.state==='installed')
过滤掉除installed
之外的所有状态,因此在安装每个新软件后,将执行其正向分支if(navigator.serviceworner.controller)
检查页面当前是否由任何(以前的)服务工作者控制。如果为true,那么我们在这里处理前面提到的更新场景console.log
将在正确安装更新的(不是第一个)服务工作程序后执行
更改
index.html
后将不会触发它。只有Service Worker代码(由serviceWorker.register
方法指向)被检查。另外请注意,通常情况下,浏览器(或至少是Chrome?)在当前软件版本下载后24小时内不会检查新软件版本。还请注意,如果服务工作者文件的普通旧HTTP缓存集使用过于激进的缓存头发送,则可能会在此处出错。很好的解释。所以我走错方向了?我如何实现在index.html
中检测到更改的预期结果?不要对index.html使用缓存优先的方法,或者确保在每次索引更改时更新sw.js。或者最好考虑应用应用程序外壳架构,这样您就不需要经常更改index.html。我也看到了注册。只有当一个全新的字段注册为服务人员时,onUpdate才会运行?如果对以前使用的文件进行了更改,则不会?或者每24小时“版本更改”是什么意思?这是说它是缓存的,缓存每24小时过期一次吗?是的,正确onupdatefound
表示找到了一个全新的服务人员文件。由于该阈值,它可能在距离上次时间不早于24小时的情况下发生。