首页 > 解决方案 > 如果页面脱机,如何从服务人员获得对索引 js 的响应

问题描述

我正在使用城市列表服务,在我的主页中使用 HTTP 请求我已经获取列表并显示在自动完成中,所以我想知道通过使用服务工作者如何将该城市列表存储在缓存中并在离线模式下使用

标签: javascriptservice-workerpwa

解决方案


看看这里

首先,您已经安装了一个服务人员。接下来,您已经知道需要拦截什么样的请求以及您希望如何响应请求。(缓存策略)。

在你的 index.html 添加

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
  .then(function(registration) {
    console.log('Registration successful, scope is:', registration.scope);
  })
  .catch(function(error) {
    console.log('Service worker registration failed, error:', error);
  });
}

然后在你的 service-worker.js 添加

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.open('cache-name').then(function(cache) {
      return cache.match(event.request).then(function (response) {
        return response || fetch(event.request).then(function(response) {
          cache.put(event.request, response.clone());
          return response;
        });
      });
    })
  );
});

这将缓存您的所有网络 GET 请求。因此,从您的下一个请求开始,它将首先检查缓存,并且仅当数据不存在时才会进行网络获取。


推荐阅读