From 4b7f847d7210c958953825517a04ca45cbc1d1d6 Mon Sep 17 00:00:00 2001 From: liuweiqing Date: Wed, 21 Feb 2024 21:23:21 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20=E5=8F=96=E6=B6=88service=20worker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/layout.tsx | 4 +-- public/service-worker.js | 60 ++++++++++++++++++++++++++++++++-------- 2 files changed, 50 insertions(+), 14 deletions(-) diff --git a/app/layout.tsx b/app/layout.tsx index 1b87dbab..f4cc025b 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -54,7 +54,7 @@ export default function RootLayout({ return ( - + `} */}
{children} diff --git a/public/service-worker.js b/public/service-worker.js index 9c9bec12..65e35831 100644 --- a/public/service-worker.js +++ b/public/service-worker.js @@ -1,22 +1,58 @@ const cacheName = "v1"; +const preCacheResources = [ + // 添加需要预缓存的资源列表 + "/.next/static", + "/public", + "/", + "/index.html", + "/styles/main.css", + "/scripts/main.js", + // 更多资源... +]; +// 安装事件:预缓存关键资源 +self.addEventListener("install", (e) => { + console.log("Service Worker: Installed"); + e.waitUntil( + caches + .open(cacheName) + .then((cache) => { + console.log("Service Worker: Caching Files"); + cache.addAll(preCacheResources); + }) + .then(() => self.skipWaiting()) + ); +}); +// 激活事件:清理旧缓存 +self.addEventListener("activate", (e) => { + console.log("Service Worker: Activated"); + e.waitUntil( + caches.keys().then((cacheNames) => { + return Promise.all( + cacheNames.map((cache) => { + if (cache !== cacheName) { + console.log("Service Worker: Clearing Old Cache"); + return caches.delete(cache); + } + }) + ); + }) + ); +}); +// 尝试从网络获取资源,并将响应克隆到缓存 const cacheClone = async (e) => { const res = await fetch(e.request); const resClone = res.clone(); - const cache = await caches.open(cacheName); await cache.put(e.request, resClone); return res; }; -const fetchEvent = () => { - self.addEventListener("fetch", (e) => { - e.respondWith( - cacheClone(e) - .catch(() => caches.match(e.request)) - .then((res) => res) - ); - }); -}; - -fetchEvent(); +// Fetch 事件:网络优先,然后缓存 +self.addEventListener("fetch", (e) => { + e.respondWith( + cacheClone(e) + .catch(() => caches.match(e.request)) + .then((res) => res || fetch(e.request)) + ); +});