What's the right way to implement offline fallback with workbox

前端 未结 1 584
-上瘾入骨i
-上瘾入骨i 2021-02-05 23:52

I am implementing PWA into my project, I have setted up the serviceworker.js, and I am using workbox.js for cache routing and strategies.

1- I add the offline pa

相关标签:
1条回答
  • 2021-02-06 00:30

    I found a way to do it right with workbox. For each route I would add a fallback method like this:

    const offlinePage = '/offline/';
    /**
     * Pages to cache
     */
    workbox.routing.registerRoute(/\/posts.|\/articles/,
      async ({event}) => {
        try {
          return await workbox.strategies.staleWhileRevalidate({
              cacheName: 'cache-pages'
          }).handle({event});
        } catch (error) {
          return caches.match(offlinePage);
        }
      }
    );
    

    In case of using network first strategy this is the method:

    /**
     * Pages to cache (networkFirst)
     */
    var networkFirst = workbox.strategies.networkFirst({
      cacheName: 'cache-pages' 
    });
    
    const customHandler = async (args) => {
      try {
        const response = await networkFirst.handle(args);
        return response || await caches.match(offlinePage);
      } catch (error) {
        return await caches.match(offlinePage);
      }
    };
    
    workbox.routing.registerRoute(
      /\/posts.|\/articles/, 
      customHandler
    );
    

    More details at workbox documentation here: Provide a fallback response to a route

    0 讨论(0)
提交回复
热议问题