Service Worker首先从缓存提供URL,并在需要时进行更新

时间:2018-05-31 08:41:38

标签: javascript service-worker progressive-web-apps

我首先看到alway cache with static assets for create PWA Offline。但是,是否可以缓存URL并在下次渲染时首先从缓存中提供URL并在需要时更新缓存?

暂时在我的PWA上,我复制了所有已查看的网址,但我无法首先提供缓存:/

我的获取事件:

self.addEventListener("fetch", event => {
  const updateCache = request => {
    return caches
      .open(CACHE_NAME)
      .then(cache => {
        return fetch(request)
          .then(response => {
            console.log(`[PWA] add page to offline ${response.url}`);
            return cache.put(request, response);
          })
          .catch(error => console.log(error));
      })
      .catch(error => console.log(error));
  };

  event.waitUntil(updateCache(event.request));

  event.respondWith(
    fetch(event.request).catch(error => {
      console.log(
        `[PWA] Network request Failed. Serving content from cache: ${error}`
      );

      // Check to see if you have it in the cache
      // Return response
      // If not in the cache, then return error page
      return caches
        .open(CACHE_NAME)
        .then(cache => {
          return cache.match(event.request).then(matching => {
            const report =
              !matching || matching.status == 404
                ? Promise.reject("no-match")
                : matching;
            return report;
          });
    })
    .catch(error => console.log(error));
    })
  );
});

1 个答案:

答案 0 :(得分:0)

您有all different cache options以及我从您的问题中了解到的内容,您希望在初始加载后从缓存(如果存在)提供内容,而不是来自网络。 “Cache falling back to the network “是实现相同目标所需的缓存类型。