在 Angular (8) 应用程序中,我想添加一个自定义离线页面(只是一个简单的 html 文件)。
我已将我的应用程序设置为 PWA(使用@angular/pwa
并配置了一切,以便它至少在在线时顺利工作)。
然而,我很难为 PWA 用户提供更新。因此,经过几个小时的尝试和错误,我决定排除index.html
来自ngsw-config.json
。这当然会产生这样的效果:index.html
每次都会被加载(还不错,因为它太小了)。如果有任何更新index.html
链接到不同的 JS 文件,这些文件会立即加载。因此,正如我之前所说,PWA 的工作原理正如我所希望的那样。
现在我想显示一个offline.html
当用户离线启动 PWA 时。所以我添加了offline.html
to ngsw-config.json
我创建了一个自定义 Service Worker,包括官方的ngsw-worker.js
:
importScripts('./ngsw-worker.js');
我还使用这个自定义服务工作者而不是官方的:
ServiceWorkerModule.register('./custom-worker.js', { enabled: true, registrationStrategy: registrationStrategy })
到目前为止,一切仍然按预期进行。行为举止就跟以前一样。现在我想在我的自定义工作线程中包含离线行为:
importScripts('./ngsw-worker.js');
self.addEventListener('fetch', function(event) {
return event.respondWith(
caches.match(event.request)
.then(function(response) {
let requestToCache = event.request.clone();
return fetch(requestToCache).then().catch(error => {
// Check if the user is offline first and is trying to navigate to a web page
if (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html')) {
// Return the offline page
return caches.match("offline.html");
}
});
})
);
});
该脚本来自:https://stackoverflow.com/a/56738140/4653997 https://stackoverflow.com/a/56738140/4653997不幸的是,这是根本不起作用的部分。现在我几乎陷入困境。我不知道下一步该做什么。
我认为服务人员是否会被处决index.html
可以加载也可以不加载。
任何帮助,将不胜感激。