javascript - Polymer 应用刷新策略

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

我们的应用程序是一个 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/

相关文章:

vue.js - 缓存 MP3 音频文件以供离线访问

javascript - 如何使用适用于 jQuery 和 AJAX 的 SortableJS 更改类别的订单 ID?

seo - Google 抓取工具是否在索引之前等待页面完成?

javascript - 如何从 HTML 元素将 `false` 传递给 polymer 组件属性?

javascript - 如何将网络通知内容复制到剪贴板

javascript - Service Worker 根据屏幕分辨率缓存不同大小的图像

javascript - 无法连接到 Firebase(JS)

javascript - 添加暂停按钮

javascript - 如何在 WinJS 上进行反向地理编码

testing - Polymer 3.0 a11ySuite 测试报错