sw.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const CACHE_NAME = 'shenze-cache-v1'; // 更新版本号强制更新
  2. const DYNAMIC_CACHE = 'shenze-dynamic-v1';
  3. const STATIC_ASSETS = [
  4. '/shenze/index.html',
  5. '/shenze/favicon.ico',
  6. '/shenze/manifest.json',
  7. // 避免缓存 version.json
  8. ];
  9. self.addEventListener('install', (event) => {
  10. event.waitUntil(
  11. caches.open(CACHE_NAME)
  12. .then(cache => cache.addAll(STATIC_ASSETS))
  13. .then(() => self.skipWaiting())
  14. );
  15. });
  16. self.addEventListener('activate', (event) => {
  17. event.waitUntil(
  18. caches.keys().then(cacheNames => {
  19. return Promise.all(
  20. cacheNames.map(cacheName => {
  21. if (cacheName !== CACHE_NAME && cacheName !== DYNAMIC_CACHE) {
  22. return caches.delete(cacheName);
  23. }
  24. })
  25. );
  26. }).then(() => self.clients.claim())
  27. );
  28. });
  29. // fetch 事件:合理区分缓存策略
  30. self.addEventListener('fetch', (event) => {
  31. const url = new URL(event.request.url);
  32. // version.json 永远走网络
  33. if (url.pathname === '/shenze/version.json') {
  34. event.respondWith(
  35. fetch(event.request)
  36. .then(response => response)
  37. .catch(() => new Response('{}', { headers: { 'Content-Type': 'application/json' } }))
  38. );
  39. return;
  40. }
  41. // index.html 及所有 HTML 页面,网络优先
  42. if (url.pathname === '/shenze/' || url.pathname.endsWith('.html')) {
  43. event.respondWith(
  44. fetch(event.request)
  45. .then(response => {
  46. // 更新缓存
  47. const copy = response.clone();
  48. caches.open(CACHE_NAME).then(cache => cache.put(event.request, copy));
  49. return response;
  50. })
  51. .catch(() => caches.match(event.request))
  52. );
  53. return;
  54. }
  55. // 其他静态资源(js/css/img/font等),缓存优先
  56. event.respondWith(
  57. caches.match(event.request).then(cachedResponse => {
  58. return cachedResponse || fetch(event.request).then(networkResponse => {
  59. if (event.request.method === 'GET' && networkResponse && networkResponse.status === 200) {
  60. const copy = networkResponse.clone();
  61. caches.open(DYNAMIC_CACHE).then(cache => cache.put(event.request, copy));
  62. }
  63. return networkResponse;
  64. }).catch(() => {
  65. return undefined;
  66. });
  67. })
  68. );
  69. });
  70. self.addEventListener('message', event => {
  71. if (event.data === 'skip-waiting') {
  72. self.skipWaiting();
  73. }
  74. });