1
votes

I see alway cache first with static assets for create PWA Offline first. But, is it possible to cache URL and serve it from cache first on next render and update the cache if needed ?

On my PWA for now, i copy all URL viewed, but i can't serve the cache first :/

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

1 Answers

0
votes

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.