[英]Service-workers blocks backbonejs?
我已經使用Backbone.js構建了一個Web應用程序,它對RESTful服務有很多調用,它的工作原理很吸引人。
我嘗試添加ServiceWorker來緩存所有先前的調用,以便它們可以脫機使用。
我實際上得到的是,我第一次撥打的電話因以下錯誤而死亡:
無法加載資源:net :: ERR_FAILED
但是在頁面重新加載時,我得到了它的緩存數據
我的服務人員獲取:
self.addEventListener('fetch', function(e) {
// e.respondWidth Responds to the fetch event
e.respondWith(
// Check in cache for the request being made
caches.match(e.request)
.then(function(response) {
// If the request is in the cache
if ( response ) {
console.log("[ServiceWorker] Found in Cache", e.request.url, response);
// Return the cached version
return response;
}
// If the request is NOT in the cache, fetch and cache
var requestClone = e.request.clone();
fetch(requestClone)
.then(function(response) {
if ( !response ) {
console.log("[ServiceWorker] No response from fetch ")
return response;
}
var responseClone = response.clone();
// Open the cache
caches.open(cacheName).then(function(cache) {
// Put the fetched response in the cache
cache.put(e.request, responseClone);
console.log('[ServiceWorker] New Data Cached', e.request.url);
// Return the response
return response;
}); // end caches.open
console.log("Response is.. ?", response)
return response;
})
.catch(function(err) {
console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
});
}) // end caches.match(e.request)
); // end e.respondWith
});
編輯:我認為不需要任何Backbone.js網絡應用程序代碼。 我使用Backbone.js模型和集合中的fetch
方法。 像https://jsonplaceholder.typicode.com/posts/1和https://jsonplaceholder.typicode.com/posts/2之類的調用
將在第一次播放時顯示此錯誤。 刷新頁面后,我確實有此信息而無需請求。 全部來自緩存。 而我仍然沒有執行的所有其他請求將保持錯誤
我看到的唯一問題是,當請求不在高速緩存中時,您將執行fetch
,但不會將 fetch
的結果返回給封閉的then
處理程序。 您需要添加return
以便擁有:
return fetch(requestClone)
.then(function(response) {
否則, then
處理器中用於fetch
的return
語句提供的任何數據都不會沿鏈向上傳輸。
我還看到您沒有返回caches.open(cacheName).then...
提供的承諾。 如果您想將響應保存在緩存中與返回結果鏈分離開,這可能很好,但是至少我要發表評論說,這就是我在這里所做的事情,而不是留給讀者以確定是否是偶然遺漏了return
聲明,還是故意這樣做的。
我搜索更多后解決了。 Backbone.js我在Web應用程序中的視圖曾經用來做:
this.listenTo(this.collection,"reset",this.render);
this.listenTo(this.collection,"add",this.addCollectionItem);
this.listenTo(this.collection,"error", this.errorRender);
當我的服務人員返回承諾時。
我必須將我的Web應用程序視圖中的一些代碼更改為如下所示:
this.collection.fetch({},{reset:true})
.then(_.bind(this.render, this))
.fail(_.bind(this.errorRender,this))
或多或少...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.