Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: googlefont cache #17

Merged
merged 1 commit into from
Jan 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
}
}