使用工作箱实现离线回退的正确方法是什么

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

我正在我的项目中实施 PWA,我已经设置了 serviceworker.js,并且我正在使用 workbox.js 进行缓存路由和策略。

1- 我在安装事件中将离线页面添加到缓存,当用户首次访问该站点时:

/**
 * Add on install
 */
self.addEventListener('install', (event) => {
  const urls = ['/offline/'];
  const cacheName = workbox.core.cacheNames.runtime;
  event.waitUntil(caches.open(cacheName).then((cache) => cache.addAll(urls)))
});

2- 使用特定的正则表达式捕获并缓存页面,例如:

https://website.com/posts/the-first-post

https://website.com/posts/

https://website.com/articles/

workbox.routing.registerRoute(
  new RegExp('/posts|/articles'),
  workbox.strategies.staleWhileRevalidate({
     cacheName: 'pages-cache' 
  })
);

3- 在没有互联网连接时捕获错误并显示离线页面

/**
 * Handling Offline Page fallback
 */
this.addEventListener('fetch', event => {
  if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
        event.respondWith(
          fetch(event.request.url).catch(error => {
              // Return the offline page
              return caches.match('/offline/');
          })
    );
  }
  else{
        // Respond with everything else if we can
        event.respondWith(caches.match(event.request)
                        .then(function (response) {
                        return response || fetch(event.request);
                    })
            );
      }
});

到目前为止,如果我访问例如:https://website.com/contact-us/ but if I visit any url within the scope I defined earlier for "pages-cache" like https://website.com/articles/231/ 这不会 return /offline 页面,因为它不在用户缓存中,我会得到一个常规的浏览器错误。

当工作箱有特定的缓存路由时,错误的处理方式存在问题。

这是申请离线回退的最佳方式吗?如何从这些路径捕获错误:“/articles”和“/posts”并显示离线页面?

Please refer as well to where there's a different approach to applying the fallack with workbox, I tried it as well same results. Not sure which is the accurate approach for this.

我找到了一种使用 Workbox 的方法。 对于每条路线,我都会添加这样的后备方法:

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

如果使用网络优先策略,这是方法:

/**
 * 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
);

此处工作箱文档中有更多详细信息:Provide a fallback response to a route