Skip to content

Commit

Permalink
chore: 取消service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
14790897 committed Feb 21, 2024
1 parent 3004ae2 commit 4b7f847
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 14 deletions.
4 changes: 2 additions & 2 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default function RootLayout({
return (
<html lang="en" className={GeistSans.className}>
<Script src="//fw-cdn.com/11368617/4047428.js" chat="true"></Script>
<Script>{`
{/* <Script>{`
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
Expand All @@ -66,7 +66,7 @@ export default function RootLayout({
});
});
}
`}</Script>
`}</Script> */}
<body className="bg-background text-foreground">
<main className="min-h-screen flex flex-col items-center">
{children}
Expand Down
60 changes: 48 additions & 12 deletions public/service-worker.js
Original file line number Diff line number Diff line change
@@ -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))
);
});

0 comments on commit 4b7f847

Please sign in to comment.