本文介绍了服务人员让我的网络变慢了!如何使用Workbox为Django工作添加离线功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已尝试使用workbox为我的Django Web App提供脱机功能,但未成功。

我已按照get started guide进行操作,并成功注册了Success the Service Worker,并从缓存中保存/提供静态和媒体资源。

存档Describe的代码:

urls.py

...
url(r'^service-worker.js', cache_control(max_age=60*60*24)(TemplateView.as_view(
    template_name="sw.js",
    content_type='application/javascript',
)), name='sw.js'),
...

base.html模板

...
<!-- bottom of body -->
<script>

  // Check that service workers are registered
        if ('serviceWorker' in navigator) {
          // Use the window load event to keep the page load performant
          window.addEventListener('load', () => {
            navigator.serviceWorker.register('{% url 'sw.js' %}');
          });
        }

</script>
...

sw.js(服务工作者)

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.2.0/workbox-sw.js');

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}

workbox.setConfig({
  debug: false
});

// workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug);


workbox.routing.registerRoute(
  /.(?:js|css)$/,
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'static-resources',
  }),
);

workbox.routing.registerRoute(
  /.(?:png|gif|jpg|jpeg|svg)$/,
  workbox.strategies.cacheFirst({
    cacheName: 'images',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  }),
);

workbox.routing.registerRoute(
  new RegExp('https://fonts.(?:googleapis|gstatic).com/(.*)'),
  workbox.strategies.cacheFirst({
    cacheName: 'googleapis',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 30,
      }),
    ],
  }),
);

之后,我决定检查性能,看看服务人员是否帮助我的应用程序比以前更快地提供缓存文件。

我在这里留下两个截图供您查看(加载时间在右下角以红色显示):

516M,无服务工作者,默认Django缓存

1.09秒,服务人员为缓存文件提供服务

在这之后,我不得不说我感到震惊,我期待着改善,但我得到了相反的结果(我在前面的步骤中做错了什么?)

之后我做了更多的测试,在其他大多数情况下,加载时间都是相似的,但我仍然看不到对服务人员的支持有多大差异,特别是在第一次访问时

但另一方面,我在想,如果我获得离线能力,那么500ms~是一个合理的价格,但甚至不是...

我将以下几行添加到服务工作者中,以便在没有网络的情况下提供页面服务:

workbox.precaching.precacheAndRoute(
  [
    '/',
    '/offline',
  ],
  {
    directoryIndex: null,
  }
);

workbox.routing.registerRoute(
  /* my urls doesn't end in html, so i didn't found another way to 
  store only the html document except using the main route of my app as reg ex

example: http://localhost:8000/participation/id/title -> html for article
         http://localhost:8000/participation/ -> html for list of articles */

      new RegExp('participation/'), 
      workbox.strategies.networkFirst({
        cacheName: 'html-resources',
      })
    );

所以现在,如果我在一些参与页面中处于离线状态,我仍然可以看到它们,但这会导致我的实际问题。

好的,因此,如果用户现在尝试在没有网络的情况下访问他以前从未访问过的页面,我想将他发送到我的脱机页面,在那里我只向他显示他处于脱机状态,他可以转到他已经访问的X个页面

我没有找到任何解决此问题的方法,我尝试了一下:

workbox.routing.registerRoute(
  ({ event }) => event.request.mode === 'navigate', //if the requests is to go to a new url
  ({ url }) => fetch(url.href,{credentials: 'same-origin'}).catch(() => caches.match('/offline')) //in case of not match send my to the offline page
);

但它根本不起作用,我怎么能做到这一点?

推荐答案

我通过将其添加到服务工作人员解决了该问题

// Fallback to offline page if nothing is found in cache
var networkFirstHandler = workbox.strategies.networkFirst({
  cacheName: 'default',
  plugins: [
    new workbox.expiration.Plugin({
      maxEntries: 10
    }),
    new workbox.cacheableResponse.Plugin({
      statuses: [200]
    })
  ]
});

const matcher = ({event}) => event.request.mode === 'navigate';
const handler = (args) => networkFirstHandler.handle(args).then((response) => (!response) ? caches.match('/offline') : response);

workbox.routing.registerRoute(matcher, handler);
// End fallback offline

这篇关于服务人员让我的网络变慢了!如何使用Workbox为Django工作添加离线功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 13:22