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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM