我正在开发一个渐进式网络应用程序。 我有一个页面正在尝试添加离线效果。 以下是我的服务人员代码:
toolbox.precache(['/mobileweb/',
'/mobileweb/index.html',
'/mobileweb/header.html',
'/mobileweb/index.html',
'/mobileweb/location-search.html',
'/mobileweb/voucher-details.html'
]);
toolbox.router.any('/mobileweb/js/(.*)', toolbox.cacheFirst);
toolbox.router.any('/mobileweb/images/(.*)', toolbox.cacheFirst);
toolbox.router.any('/mobileweb/css/(.*)', toolbox.cacheFirst);
toolbox.router.any('/mobileweb/fonts/(.*)', toolbox.cacheFirst);
//toolbox.router.get('/(.*)', toolbox.fastest, {origin: 'https://example.in/mp_webapp/webwallt'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://example.in/mobileweb/css'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://example.in/mobileweb/images'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://example.in/mobileweb/js'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://s3-ap-southeast-1.amazonaws.com'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://d15xs3htl97jic.cloudfront.net'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://bit.ly'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://maps.googleapis.com'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://example.in/mp_webapp/webwallet/ajax'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://maps.google.com'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://csi.gstatic.com/'});
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://maps.gstatic.com/'});
this.addEventListener('fetch', function(event) {
// console.log(event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
console.log(event.request.url);
return response || fetch(event.request);
})
);
});
现在,从上面的代码中,我可以缓存所有内容。 当我重新加载页面两次或三次时,我可以看到每个请求都是通过控制台中的网络选项卡来自服务工作线程。 现在,如果我尝试在关闭 WiFi 后重新加载页面,那么我不会看到空白屏幕。我看到我的页面包含已预先缓存的内容。但我无法看到完整的页面,因为当网络关闭时,填充页面的 ajax 就会消失。 谁能告诉我如何缓存我的 ajax 响应,以便我获得无缝的体验。缓存所有 ajax 响应的代码:
toolbox.router.get('/(.*)', toolbox.cacheFirst, {origin: 'https://example.in/mp_webapp/webwallet/ajax'});
最佳答案
最后需要添加一个额外的步骤才能在离线时运行。
self.toolbox.router.default = self.toolbox.networkFirst;
self.toolbox.options.networkTimeoutSeconds = 86400;
self.addEventListener('install', function(event) {
return event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function(event) {
return event.waitUntil(self.clients.claim());
});
关于使用 Service Worker 进行 Ajax 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37819503/