简体   繁体   English

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

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

I see alway cache first with static assets for create PWA Offline first. 我首先看到总是带有静态资产的缓存,以便首先离线创建PWA。 But, is it possible to cache URL and serve it from cache first on next render and update the cache if needed ? 但是,是否可以缓存URL并在下一次渲染时首先从缓存中提供它并在需要时更新缓存?

On my PWA for now, i copy all URL viewed, but i can't serve the cache first :/ 现在在我的PWA上,我复制所有查看的URL,但是我不能先提供缓存:/

My fetch event : 我的提取事件:

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

Here are all different cache options you have and from what I understand from your question, you want to serve your content from cache(when present) after the initial load and it not present, from network. 这是您拥有的所有不同缓存选项 ,根据我对问题的了解,您希望在初始加载后从缓存(如果存在)通过网络提供内容(如果不存在)。 " Cache falling back to the network " is the type of cache you need to implement to achieve the same. 缓存回落到网络 ”是您需要实现以实现相同缓存的类型。

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

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