技术解析

谷歌家 googleapis.com 抽的厉害,怎样才能在国内正常的调用 workbox 的功能呢?
0
1975-03-03 11:28:55
idczone

外网访问很正常,国内不稳定时有时无,导致 service worker 依赖的 workbox 常常失效。怎样才能在国内正常使用 workbox 功能呢?( workbox-sw.js 的文件中还有依赖其他谷歌 api,单独下载 workbox-sw.js 到本地还是不行。)

service-worker.js

console.log('Hello from service-worker.js');

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

if (workbox) {
  console.log("Yes! Workbox is loaded");

  workbox.precaching.precacheAndRoute([
    {
      "url": "/",
      "revision": "1"
    }
  ]);

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

  workbox.routing.registerRoute(
    /\.(?:png|gif|jpg|jpeg|svg)$/,
    workbox.strategies.cacheFirst({
      cacheName: 'cache-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,
        }),
      ],
    }),
  );
} else {
  console.log("No! Workbox didn't load");
}


跳一次?

这个文章的最后提到了阿里 cdn,你可以替换一下
http://taobaofed.org/blog/2018/08/08/workbox3/

https://github.com/magicdawn/magicdawn/blob/master/md/fe/service-worker/workbox/0.mdjsdelivr npm cdn 加载,不喜欢 jsdelivr 可以改成 unpkg.com
version 可以具体一点

数据地带为您的网站提供全球顶级IDC资源
在线咨询
专属客服