From fc817d4d7378d1ae317d88f60b13dbd03da572e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=AB=E8=B0=B7=E5=89=91=E4=BB=99?= Date: Tue, 28 Jun 2022 00:58:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5service-worker=E7=9A=84?= =?UTF-8?q?=E4=B8=BB=E5=8A=A8=E6=BF=80=E6=B4=BB=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service-worker.js | 68 ++++++++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 30 deletions(-) diff --git a/service-worker.js b/service-worker.js index 6603e5df..9c68d71c 100644 --- a/service-worker.js +++ b/service-worker.js @@ -6435,39 +6435,47 @@ const cachesMap = new Map([ ] ]); +// 安装阶段跳过等待,直接进入 active +self.addEventListener('install', function (event) { + event.waitUntil(self.skipWaiting()); +}); + self.addEventListener('activate', function(event) { console.debug("Service Worker activate"); - + event.waitUntil( - caches.keys().then(function(keyList) { //所有的现存的缓存大分类列表 - return Promise.all( - keyList.map(async function(key) { - if (cacheName !== key) { //如果不在当前的缓存列表里就删除 - console.debug("未检测到该缓存分类,删除", key); - return caches.delete(key); - } else { - const cache = await caches.open(key); - const requests = await cache.keys(); - console.debug("检测已有缓存分类", key); - return Promise.all( - requests.map(async function(request) { - const url = new URL(request.url); - const baseUrl = new URL(".", location); - const path = url.pathname; - const relativePath = (url.origin + path).replace(baseUrl.origin + baseUrl.pathname, ""); - const oldmd5 = url.searchParams.get("md5"); //老的md5值 - const md5 = cachesMap.get(relativePath); //记录的md5值 - //console.debug("检测缓存条目", url, relativePath, oldmd5, md5); - if (!md5 || md5 !== oldmd5) { - console.debug("删除版本不匹配的缓存", request); - return cache.delete(request); - } - }) - ); - } - }) - ); - }) + Promise.all([ + self.clients.claim(), + caches.keys().then(function(keyList) { //所有的现存的缓存大分类列表 + return Promise.all( + keyList.map(async function(key) { + if (cacheName !== key) { //如果不在当前的缓存列表里就删除 + console.debug("未检测到该缓存分类,删除", key); + return caches.delete(key); + } else { + const cache = await caches.open(key); + const requests = await cache.keys(); + console.debug("检测已有缓存分类", key); + return Promise.all( + requests.map(async function(request) { + const url = new URL(request.url); + const baseUrl = new URL(".", location); + const path = url.pathname; + const relativePath = (url.origin + path).replace(baseUrl.origin + baseUrl.pathname, ""); + const oldmd5 = url.searchParams.get("md5"); //老的md5值 + const md5 = cachesMap.get(relativePath); //记录的md5值 + //console.debug("检测缓存条目", url, relativePath, oldmd5, md5); + if (!md5 || md5 !== oldmd5) { + console.debug("删除版本不匹配的缓存", request); + return cache.delete(request); + } + }) + ); + } + }) + ); + }) + ]) ); });