Skip to content

Commit

Permalink
Merge pull request #17 from MliKiowa/main
Browse files Browse the repository at this point in the history
fix: googlefont cache
  • Loading branch information
D-Sketon authored Jan 13, 2024
2 parents afd07fa + 2948981 commit 71dc03a
Showing 1 changed file with 32 additions and 21 deletions.
53 changes: 32 additions & 21 deletions source/js/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ const PreCache = [
'/js/script.js'
];

const CacheDomain = [
"fonts.googleapis.com"
];

// 安装时预加载必要内容
self.addEventListener('install', (event) => {
console.log(`Service Worker ${VERSION} installing.`);
Expand All @@ -17,27 +21,34 @@ self.addEventListener('install', (event) => {
);
});

self.addEventListener('fetch', (event) => {
// 检查请求是否为 POST 或带有查询参数的 GET 这样可用避免错误缓存
if (event.request.method === 'POST' || (event.request.method === 'GET' && event.request.url.indexOf('?') !== -1)) {
event.respondWith(fetch(event.request));
async function cacheRequest(request) {
const responseToCache = await fetch(request);
const responseToCacheClone = responseToCache.clone();
const cache = await caches.open(VERSION);
cache.put(request, responseToCacheClone);
return responseToCache;
}

async function respondRequest(request) {
const response = await caches.match(request);
if (response) {
return response;
}
return cacheRequest(request);
}

self.addEventListener('fetch', function (event) {
var url = new URL(event.request.url);
// 检查请求的域名是否在 CacheDomain 中
if (CacheDomain.includes(url.hostname)) {
event.respondWith(respondRequest(event.request));
} else {
event.respondWith(
caches.match(event.request)
.then((response) => {
if (response) {
return response;
}
return fetch(event.request).then((responseToCache) => {
var responseToCacheClone = responseToCache.clone();
caches.open(VERSION).then((cache) => {
cache.put(event.request, responseToCacheClone);
});
return responseToCache;
});
}
)
);
// 检查请求是否为 POST 或带有查询参数的 GET 这样可避免错误缓存
if (event.request.method === 'POST' || (event.request.method === 'GET' && event.request.url.indexOf('?') !== -1)) {
event.respondWith(fetch(event.request));
} else {
event.respondWith(respondRequest(event.request));
}
}
});

Expand Down Expand Up @@ -65,4 +76,4 @@ if ('serviceWorker' in navigator) {
.catch((error) => {
console.log('Service Worker 注册失败: ', error);
});
}
}

0 comments on commit 71dc03a

Please sign in to comment.