服务工作者在React应用程序中刷新后导致空白页

时间:2017-09-30 08:09:33

标签: node.js azure express socket.io service-worker

我有一个部署到Azure的Node应用程序,其中一个测试分支指向一个临时实例,一个主分支指向prod部署。我的应用程序在本地应用程序的所有实例上都能正常工作,但是生产和分段存在一个问题,如果它们已经被缓存,它们将不会加载,并且在刷新后将显示为空白,最后将在缓存重置时正常工作。

每当我在生产中刷新页面时,它都是空白的。服务工作者正在运行(我可以在chrome serviceworkers-internal工具中看到它),但页面永远不会加载。生成的文件引用是正确的。您可以在此处查看正在发生的事情的示例:Live Site然后您还可以看到测试站点也失败,并且部署了完全相同的代码:Test Site

整个ServiceWorker实现都是create-react-app开箱即用的。我花了几个小时试图在反应 - 样板和create-react-app repos下的各种GitHub问题中跟踪这个错误,并且没有一个真正能够超越限制页面缓存,我试图用没有用:

的index.html

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>

您可以在the repo that hosts all of this code.

找到有关任何代码的任何问题的代码

我只是想用React / Node弄湿我的脚,所以我在墙上并没有真正看到如何在不完全剥离ServiceWorker注册的情况下解决这个问题。

编辑:我从index.js文件中完全删除了ServiceWorker代码,并且视线重新加载,现在没有任何问题。我需要完成一个步骤才能让ServiceWorker从缓存中正确地重新加载页面吗?

1 个答案:

答案 0 :(得分:0)

万一有人发现像我这样的问题,答案是禁用服务工作者文件(对我来说是service-worker.js)和index.html上的浏览器缓存,并永久缓存其余部分。

进行更改后,它将显示旧版本的应用程序继续运行,并在启动时检测到有新版本。如果像我一样,您不缓存静态资源,则当它尝试获取旧版本时,它会得到404,从而导致空白页。如果您第二次刷新,它将获取该应用程序的新版本。

我向我的代码中添加了一些代码,以通过修改 registerServiceWorker.js

5秒后自动重新加载
function registerValidSW(swUrl) {
console.debug('Registering serviceWorker URL [' + 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.
                        reportInfo('App has been updated. This page will refresh in 5 seconds.');
                        setInterval(()=>window.location.reload(), 5000);
                    } else {
                        // At this point, everything has been precached.
                        // It's the perfect time to display a
                        // "Content is cached for offline use." message.
                        reportInfo('App is cached for offline use.');
                    }
                }
            };
        };
    })
    .catch(error => {
        reportError('Error during service worker registration:', error);
    });

}

相关问题