【问题标题】:Polymer app refresh strategyPolymer 应用刷新策略
【发布时间】:2018-01-13 05:00:14
【问题描述】:

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

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

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

【问题讨论】:

  • 注册Service Worker时,可以监听更新,检测到更新时向Service Worker发送消息。在您的 service worker 中,您可以收听这些消息并对其采取行动(例如,调用 skipWaiting,导致下一个 service worker 立即接管)

标签: javascript polymer service-worker polymer-2.x


【解决方案1】:

这里是准备好的代码,都描述了如何处理 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);
        });
     }

【讨论】:

    猜你喜欢
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多