mo 1 year ago
parent
commit
482b132d2c
2 changed files with 25 additions and 17 deletions
  1. 1 0
      dev-dist/registerSW.js
  2. 24 17
      index.html

+ 1 - 0
dev-dist/registerSW.js

@@ -0,0 +1 @@
+if('serviceWorker' in navigator) navigator.serviceWorker.register('/dev-sw.js?dev-sw', { scope: '/', type: 'classic' })

+ 24 - 17
index.html

@@ -177,23 +177,30 @@
       }, true)
 
       if ('serviceWorker' in navigator) {
-        navigator.serviceWorker.addEventListener('install', event => {
-          navigator.serviceWorker.skipWaiting()
-          // 预缓存其他静态内容
-        })
-        navigator.serviceWorker.addEventListener('controllerchange', () => {
-          console.log('控制更新刷新')
-          window.location.reload();
-        })
-        let flag = caches.keys().length > 0
-        console.log(caches.keys(), 'caches.keys()', `是否有缓存${flag}`);
-        caches.keys().then(function (cacheNames) {
-          cacheNames.forEach(function (cacheName) {
-            caches.delete(cacheName);
-          });
-          if (flag) {
-            window.location.reload()
-          }
+
+        // let flag = caches.keys().length > 0
+        // console.log(caches.keys(), 'caches.keys()', `是否有缓存${flag}`);
+        // caches.keys().then(function (cacheNames) {
+        //   cacheNames.forEach(function (cacheName) {
+        //     caches.delete(cacheName);
+        //   });
+        //   if (flag) {
+        //     window.location.reload()
+        //   }
+        // });
+        navigator.serviceWorker.register('/dev-sw.js?dev-sw').then(reg => {
+          console.log('组测', reg)
+          reg.onupdatefound = () => {
+            const installingWorker = reg.installing;
+            console.log('更新===>')
+            installingWorker.onstatechange = () => {
+              if (installingWorker.state === 'installed' &&
+                navigator.serviceWorker.controller) {
+                // Preferably, display a message asking the user to reload...
+                location.reload();
+              }
+            };
+          };
         });
       }