Best practices for detecting offline state in a service worker

前端 未结 1 688
走了就别回头了
走了就别回头了 2020-12-05 06:38

I have a service worker that is supposed to cache an offline.html page that is displayed if the client has no network connection. However, it sometimes believes

相关标签:
1条回答
  • 2020-12-05 07:34

    navigator.onLine and the related events can be useful when you want to update your UI to indicate that you're offline and, for instance, only show content that exists in a cache.

    But I'd avoid writing service worker logic that relies on checking navigator.onLine. Instead, attempt to make a fetch() unconditionally, and if it fails, provide a backup response. This will ensure that your web app behaves as expected regardless of whether the fetch() fails due to being offline, due to lie-fi, or due to your web server experiencing issues.

    // Other fetch handler code...
    
    if (event.request.mode === 'navigate') {
      return event.respondWith(
        fetch(event.request).catch(() => caches.match(OFFLINE_URL))
      );
    }
    
    // Other fetch handler code...
    
    0 讨论(0)
提交回复
热议问题