繁体   English   中英

Service Worker首先从缓存提供URL,然后根据需要更新

[英]Service Worker serve URL from cache first and update if needed

我首先看到总是带有静态资产的缓存,以便首先离线创建PWA。 但是,是否可以缓存URL并在下一次渲染时首先从缓存中提供它并在需要时更新缓存?

现在在我的PWA上,我复制所有查看的URL,但是我不能先提供缓存:/

我的提取事件:

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));
    })
  );
});

这是您拥有的所有不同缓存选项 ,根据我对问题的了解,您希望在初始加载后从缓存(如果存在)通过网络提供内容(如果不存在)。 缓存回落到网络 ”是您需要实现以实现相同缓存的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM