无法访问服务器时显示脱机缓存 [英] Show offline cache when server is unreachable
问题描述
当服务器关闭时,是否可以显示我网站的离线缓存?
Is it possible to show an offline cache of my website when the server is down?
我可以找到关于离线页面的所有示例都与客户端处于脱机状态有关。如果无法访问服务器,我需要向用户显示我的网站的缓存版本。
All the examples I can find regarding offline pages has to do with the client being offline. What I need is to show the user a cached version of my site if the server can't be reached.
我读过缓存清单,但它已被删除,导致许多问题。
I've read about the Cache Manifest in HMTL 5 but it's getting removed and it causes to many problems.
如果不使用任何其他负载均衡服务器,可以做些什么?
What can be done without using any other loadbalancing servers and such?
推荐答案
我最近了解到,使用Fetch API和服务工作者很简单:
I recently learned that with Fetch API and service workers its dead simple:
首先,注册服务工作者:
First, you register the Service worker:
if (!navigator.serviceWorker) return;
navigator.serviceWorker.register('/sw.js')
然后将其配置为缓存所需的内容:
Then configure it to cache whats needed:
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(staticCacheName).then(function(cache) {
return cache.addAll([
'/',
'js/main.js',
'css/main.css',
'imgs/icon.png',
]);
})
);
});
如果电话没有响应,请使用Fetch API获取缓存的和平:
And use Fetch API to get cached peaces if no response from the call:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
如果需要获得缓存版 如果服务器已关闭,请尝试喜欢:
if need to get cached version only if server is down, try something like:
self.addEventListener('fetch', function(event) {
event.respondWith(
return fetch(event.request).then(function(response) {
if (response.status !== 200) {
caches.match(event.request).then(function(response) {
return response;
}).catch(function(error) {
console.error('Fetching failed:', error);
throw error;
});
})
);
});
p.s。使用Fetch API似乎比实现旧的和令人讨厌的XMLHttpRequest更好。
p.s. using Fetch API seems much nicer way than implementing old and nasty XMLHttpRequest.
这篇关于无法访问服务器时显示脱机缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!