VUE - 使用 service-worker 缓存静态文件

VUE - 使用 service-worker 缓存静态文件

  

 开发环境:vue2,vuecli4

 

在main.js 引用 sw配置

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./sw.js').then(function (registration) {
    console.log('Registration successful, scope is:', registration.scope);
  }).catch(function (error) {
    console.log('Service Worker registration failed, error:', error);
  });
}

 

 

在 public 中 创建 sw.js 文件

文中引用的是 阿里的CDN,如需引用本地文件,可在 github上下载:https://github.com/GoogleChrome/workbox/releases/tag/v3.3.0,把文件夹放在public 文件夹下,修改 sw.js中的引用路径。

 

 

'use strict';
//使用阿里的CDN
importScripts('https://g.alicdn.com/kg/workbox/3.3.0/workbox-sw.js');

workbox.setConfig({
  modulePathPrefix: 'https://g.alicdn.com/kg/workbox/3.3.0/'
});

if (workbox) {
  console.log(`Yay! Workbox is loaded`);
} else {
  console.log(`Boo! Workbox didn't load`);
}
workbox.routing.registerRoute(
  // Cache CSS files
  /.*\.css/,
  // 使用缓存,但尽快在后台更新
  workbox.strategies.staleWhileRevalidate({
    // 使用自定义缓存名称
    cacheName: 'css-cache',
  })
);
workbox.routing.registerRoute(
  // 缓存JS文件
  /.*\.js/,
  // 使用缓存,但尽快在后台更新
  workbox.strategies.staleWhileRevalidate({
    // 使用自定义缓存名称
    cacheName: 'js-cache',
  })
);

// 模型缓存
workbox.routing.registerRoute(
  new RegExp('http://tile.railplus.com/'),
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'model-cache',
  })
);

// 模型缓存
workbox.routing.registerRoute(
  new RegExp('.+\.b3dm$'),
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'model-cache',
  })
);

// 模型缓存
workbox.routing.registerRoute(
  new RegExp('.+\.gltf$'),
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'model-cache',
  })
);
// 模型缓存
workbox.routing.registerRoute(
  new RegExp('.+\.glb$'),
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'model-cache',
  })
);

// workbox.routing.registerRoute(
//   // 缓存gravatar文件
//   new RegExp('https://cdn\.v2ex\.com/'),
//   // 如果缓存可用,请使用它
//   workbox.strategies.cacheFirst({
//     // 使用自定义缓存名称
//     cacheName: 'gravatar-cache',
//     plugins: [
//       new workbox.expiration.Plugin({
//         // 缓存最多30天
//         maxAgeSeconds: 30 * 24 * 60 * 60,
//       })
//     ],
//   })
// );

 

 

如下这些文件是从缓存读取的,标识为 (serviceworker)

 

 

 

 

 配置:

大部分路由都内置的缓存策略来处理的。

  • Stale While Revalidate(重新验证过期)
    • 当前策略会在缓存有效的情况下使用缓存响应,同时在后台使用网络更新缓存。(如果缓存无效的情况下,会等到网络请求响应再使用。)这是一种相对安全的策略,意味着用户会定期的更新缓存 。缺点就是,它总是请求网络,会占用用户的带宽。
  • Network First(网络优先)
    • 当前策略会优先从网络请求并响应,如果接到响应,将把它传给浏览器,同时进行缓存。如果网络请求失败,会使用最新的缓存资源进行响应。
  • Cache First(缓存优先)
    • This strategy will check the cache for a response first and use that if one is available. If the request isn’t in the cache, the network will be used and any valid response will be added to the cache before being passed to the browser.
    • 当前策略会检查缓存资源是否有效,如果有效,会优先使用缓存进行响应。如果请求的资源不在缓存中,会再请求网络,并将有效的响应先加载到缓存中,再传给浏览器使用。
  • Network Only(仅网络)
    • 强制从网络请求资源。
  • Cache Only(仅缓存)
    • 强制从缓存请求资源。
workbox.routing.registerRoute(
  match,
  new workbox.strategies.StaleWhileRevalidate()
);
 
workbox.routing.registerRoute(
  match,
  new workbox.strategies.NetworkFirst()
);
 
workbox.routing.registerRoute(
  match,
  new workbox.strategies.CacheFirst()
);
 
workbox.routing.registerRoute(
  match,
  new workbox.strategies.NetworkOnly()
);
 
workbox.routing.registerRoute(
  match,
  new workbox.strategies.CacheOnly()
);

 

 

 路由匹配实例

workbox.routing.registerRoute(
  '/logo.png',
  handler
);

workbox.routing.registerRoute(
  'https://some-other-origin.com/logo.png',
  handler
);

workbox.routing.registerRoute(
  new RegExp('\\.js$'),
  jsHandler
);
 
workbox.routing.registerRoute(
  new RegExp('\\.css$'),
  cssHandler
);

workbox.routing.registerRoute(
  new RegExp('/blog/\\d{4}/\\d{2}/.+'),
  handler
);

workbox.routing.registerRoute(
  new RegExp('.+/blog/\\d{4}/\\d{2}/.+'),
  handler
);


workbox.routing.registerRoute(
  new RegExp('.+\\.js$'),
  jsHandler
);
 
workbox.routing.registerRoute(
  new RegExp('.+\\.css$'),
  cssHandler
);

const matchFunction = ({url, event}) => {
  // Return true if the route should match
  return false;
};
 
workbox.routing.registerRoute(
  matchFunction,
  handler
);

 

 

 

 

参考:https://www.jianshu.com/p/8f3ad5021b0a 

参考:https://blog.csdn.net/lw001x/article/details/103694534

 

posted @ 2022-02-22 10:25  无心々菜  阅读(1792)  评论(0编辑  收藏  举报