gpt4 book ai didi

javascript - ServiceWorker 无法离线工作

转载 作者:行者123 更新时间:2023-11-29 16:45:04 26 4
gpt4 key购买 nike

我有一个简单的 service worker

安装

self.addEventListener('install', function(event) {
console.log('Service Worker Install...');
// pre cache a load of stuff:
event.waitUntil(
caches.open(CURRENT_CACHES.prefetch)
.then(function(cache) {
return cache.addAll([
'/android-chrome-192x192.png',
'/android-chrome-512x512.png',
'/apple-touch-icon.png',
'/browserconfig.xml',
'/favicon-16x16.png',
'/favicon-32x32.png',
'/favicon.ico',
'/favicon.png',
'/mstile-150x150.png',
'/safari-pinned-tab.svg',
'/app.css',
'/bundle.js',
'/sw.js'
])
.then(function(){
console.log('Caches added');
})
.catch(function(error){
console.error('Error on installing');
console.error(error);
});
})
)
});

激活

self.addEventListener('activate', function(event) {
console.log('Service Worker Activate...');
// Delete all caches that aren't named in CURRENT_CACHES.
var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
return CURRENT_CACHES[key];
});

event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (expectedCacheNames.indexOf(cacheName) === -1) {
// If this cache name isn't present in the array of "expected" cache names, then delete it.
console.log('Deleting out of date cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});

获取

self.addEventListener('fetch', function(event) {
console.log('Service Worker Fetch...');

event.respondWith(
caches.match(event.request)
.then(function(response) {
if(event.request.url.indexOf('facebook') > -1){
return fetch(event.request);
}
if(response){
console.log('Serve from cache', response);
return response;
}
return fetch(event.request);
})
.catch(function(error){
console.error('Error on fetching');
console.error(error);
})
);
});

虽然这有效,但我在缓存中看到所有内容都正确缓存:

enter image description here

当我关闭网络并刷新时,我得到:获取脚本时发生未知错误。对于 service worker。

enter image description here

难道 service worker 应该已经在那里了吗?为什么要重新获取?

最佳答案

在安装步骤中,您必须缓存 //index.html,或者您可以在获取请求后缓存它们:

self.addEventListener('fetch', function(event) {
console.log('Service Worker Fetch...');

event.respondWith(
caches.match(event.request)
.then(function(response) {
if(event.request.url.indexOf('facebook') > -1){
return fetch(event.request);
}
if(response){
console.log('Serve from cache', response);
return response;
}
return fetch(event.request)
.then(response =>
caches.open(CURRENT_CACHES.prefetch)
.then((cache) => {
// cache response after making a request
cache.put(event.request, response.clone());
// return original response
return response;
})
)

关于javascript - ServiceWorker 无法离线工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42333355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com