gpt4 book ai didi

javascript - Polymer 应用刷新策略

转载 作者:行者123 更新时间:2023-12-04 01:34:29 25 4
gpt4 key购买 nike

我们的应用程序是一个 Polymer 2 单页应用程序,我们有一些自定义构建步骤来生成资源的版本文件 (gulp-rev-all)。一切正常,但我们需要实现应用程序的安全刷新。我们正在做的是,我们将最新安装的 git commit 保存在与应用程序一起提供的文件中,我们每隔一段时间提取该文件并提醒用户有新版本可用并要求他们单击按钮刷新应用程序。

问题是我们正在使用带有预缓存的 Service Worker,这是默认的 Polymer 构建提供的。这意味着当我们执行 location.reload() 时,我们实际上是从 service worker 而不是从服务器获取内容 (index.html)。

所以问题是:我们如何强制 service worker 失效并强制重新刷新 service-worker.js 和 index.html?

最佳答案

这里是现成的代码,都描述了如何处理 service worker ;

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').then(function(reg) {
// updatefound is fired if sw.js changes.
reg.onupdatefound = function() {
// The updatefound event implies that reg.installing is set; see
// https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
var installingWorker = reg.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case '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 the page's interface.
console.log('New or updated content is available.');
// Need to hard refresh when new content is available
location.reload(true);
} 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 now available offline!');
}
break;
case 'redundant':
console.error('The installing service worker became redundant.');
break;
}
};
};

}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
}

关于javascript - Polymer 应用刷新策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48233171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com