【问题标题】:Show offline cache when server is unreachable服务器不可达时显示离线缓存
【发布时间】:2017-11-13 10:21:17
【问题描述】:

当服务器关闭时是否可以显示我的网站的离线缓存?

我能找到的所有关于离线页面的例子都与客户端离线有关。如果无法访问服务器,我需要向用户显示我网站的缓存版本。

我已阅读 HMTL 5 中的 Cache Manifest,但它已被删除,并导致许多问题。

不使用任何其他负载平衡服务器等可以做什么?

【问题讨论】:

  • 你看过localStorage吗?
  • 如果无法访问服务器,这将如何工作?我仍然需要在缓存中的某处加载一些 javascript?或者您可能正在考虑将它与 Cache Manifest 结合使用?
  • 那个 javascript 将是服务工作者。
  • 您能详细说明一下吗? :)
  • 使用服务工作者可以缓存资源和数据。看stackoverflow.com/a/28483715/1203628

标签: javascript html service-worker offline-caching


【解决方案1】:

我最近了解到,使用 Fetch API 和服务工作者非常简单:

首先,注册 Service Worker:

  if (!navigator.serviceWorker) return;

  navigator.serviceWorker.register('/sw.js')

然后将其配置为缓存所需的内容:

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(staticCacheName).then(function(cache) {
      return cache.addAll([
        '/',
        'js/main.js',
        'css/main.css',
        'imgs/icon.png',      
      ]);
    })
  );
});

如果调用没有响应,则使用 Fetch API 获取缓存的和平:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});

如果需要获取缓存版本如果服务器关闭,请尝试以下操作:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    return fetch(event.request).then(function(response) {
     if (response.status !== 200) {        
       caches.match(event.request).then(function(response) {
         return response;
       }).catch(function(error) {
         console.error('Fetching failed:', error);
         throw error;
      });
    })
  );
});

附言使用 Fetch API 似乎比实现旧的和讨厌的 XMLHttpRequest 要好得多。

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2016-10-25
    • 2019-08-10
    • 2011-12-22
    • 2021-03-18
    相关资源
    最近更新 更多