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

放肆的年华 提交于 2019-12-03 08:37:32

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!