使用工作箱实现离线回退的正确方法是什么 [英] What's the right way to implement offline fallback with workbox

查看:43
本文介绍了使用工作箱实现离线回退的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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- 当用户第一次访问网站时,我将离线页面添加到缓存:安装事件:

/**
 * 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/ 但如果我访问我之前为 "pages-cache" 定义的范围内的任何 url,例如 https://website.com/articles/231/ 这不会返回/offline 页面,因为它不在用户缓存中,我会得到常规浏览器错误.

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.

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

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?

另请参阅此答案,其中有不同的使用工作箱应用fallack的方法,我也尝试过结果.不确定哪种方法是准确的.

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.

推荐答案

我找到了一种使用 workbox 正确解决问题的方法.对于每条路线,我会添加一个像这样的回退方法:

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

这篇关于使用工作箱实现离线回退的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆