ServiceWorkers:首先返回缓存响应并获取响应异步

时间:2017-09-01 22:55:09

标签: javascript caching web service-worker

我想要与服务工作者一起缓存易失性数据。我的想法是首先返回可能过时的缓存匹配,同时触发获取请求,并在获取成功时返回该数据。

这是我要为我要缓存的非易失性数据运行的代码:

<div class="btn-primary">This is a test</div>

如何异步返回return e.respondWith( caches.match(request.url).then(function(cacheResponse) { // Found it in the cache if (cacheResponse) { console.log('[ServiceWorker] Found it in Cache') return cacheResponse // Not in the cache } else { console.log('[ServiceWorker] Not in Cache') return fetch(request).then(function(fetchResponse) { console.log('[ServiceWorker] Fetched from API', fetchResponse) // don't cache errors if (!(fetchResponse && fetchResponse.status === 200)) { console.log('[ServiceWorker] Fetch error, no cache') return fetchResponse } return caches.open(cacheName).then(function(cache) { cache.put(request.url, fetchResponse.clone()) console.log('[ServiceWorker] Fetched and Cached Data', request.url) return fetchResponse }) }) } }) ) cachedResponse?这可能吗?

更新

我已经阅读了Jake Archibald的离线食谱,在那里他谈到了cache then network,这正是我想要做的,但似乎你需要在任何地方添加代码在你想要的地方拨打电话,然后通过网络&#39;服务。

我希望有一种方法可以直接从服务工作者那里做到这一点,虽然我不确定它是否可能,因为一旦你使用缓存数据返回,你怎么能返回获取数据没有从页面再次提出完全相同的请求?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

据我所知,无法从SW返回两个回复到页面。

例如,您可以使用PostMessageBroadcast Channel API将SW中的消息发送到包含最新数据的页面。基本上你会使用Fetch API从页面请求一些东西,然后从SW返回缓存的数据,同时发起网络请求,然后用从网络收到的任何SW刷新缓存,最后如果响应是什么的话新的,通过PostMessage通知页面&#34;嘿,有新版本可用,请点击此处:{data}&#34;。

但是,这可能不比你在脱机食谱中看到的更好,实际上可以让你写更多的代码。您可能需要以某种方式管理来自SW的消息(包含新数据),并跟踪要在页面上更新的数据等。

如果我理解正确的话,我会怎么做:在一个可以用来代替简单的Fetch请求的函数中概括脱机Cookbook的想法并让它返回一个Promise。通过代码并使用customFetch()调用替换fetch()调用并将所有Caches API / SW逻辑保留在其他位置应该相当简单。