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

寵の児 提交于 2019-12-04 12:32:04

问题


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 page to cache on install event, when a user first visit the site:

/**
 * 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- Catch & cache pages with a specific regex, like these:

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- Catch errors and display the offline page, when there's no internet connection.

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

Now this is working for me so far if I visit for example: 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/ this would not return the /offline page since it's not in the user cache, and I would get a regular browser error.

There's an issue in how errors are handled, when there's a specific caching route by workbox.

Is this the best method to apply for offline fallback? how can I catch errors from these paths: '/articles' & '/posts' and display an offline page?

Please refer as well to this answer 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.


回答1:


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



来源:https://stackoverflow.com/questions/53503761/whats-the-right-way-to-implement-offline-fallback-with-workbox

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