2012-07-16 102 views
0

我一直在體驗最初似乎是間歇性問題,其中我的應用程序不能脫機工作。如何確保下載所有應用程序緩存資源?

的一些細節對我的應用程序:

  • 入口點到我的應用程序是一個登錄頁面
  • 所有在我的應用程序頁面,W /登錄頁面的例外,顯示動態數據。爲了確保顯示動態數據的頁面不被緩存,我選擇只在Login頁面的html元素中包含manifest屬性。
  • 清單文件中列出的資產總大小大約爲1MB。我拿

的步驟來重現問題(假設我沒有緩存的瀏覽器/設備上的applicationCache資源):

  • 導航到登錄頁面(applicationCache資源將開始下載)
  • 立即登錄該應用
  • 轉到下線,並要求離線資源
  • 通知瀏覽器無法從applicationCache
  • 服務資源

雖然我沒有任何具體的證據,但我最終發現的是,從瀏覽器導航到Login頁面,而瀏覽器正在檢索applicationCache資產,中斷appCache資源的下載並導致不能使用離線資源在離線時提供服務。這是預期的瀏覽器行爲?如果我等待足夠的時間並讓瀏覽器有機會下載資產,則可使用脫機功能。

爲了確保脫機功能,我是否需要阻止用戶從Login頁導航,直到applicationCache緩存事件被觸發?

+0

AppCache更新是原子的,要麼整個事情被緩存或沒有被緩存。 – robertc 2012-07-16 21:18:58

+0

從我在平板電腦上看到的一部分資產可以使用dl'd,但如果它們不是全部都是dl'd,則脫機功能無法工作。我能夠確認,通過導航離開登錄頁面,然後查看網站設置來查看我的應用程序正在使用的存儲量。 似乎沒有暴露的API會報告何時中斷/不完整的資產發生。我可以確保離線功能的唯一方法是阻止用戶從登錄頁面導航,直到緩存事件被觸發。 我很樂意接受。 – 2012-07-17 00:08:44

回答

1

這是預期的瀏覽器行爲?

這確實是有意的行爲。見http://diveintohtml5.info/offline.html#debugging

if even a single resource listed in your cache manifest file fails to download properly, the entire process of caching your offline web application will fail. Your browser will fire the error event, but there is no indication of what the actual problem was.

一個解決方案,我能想到的將是檢查beforeunload如果該window.applicationCache.status或者是checkingdownloading

或者您可能能夠在用戶localStorage中設置一個標誌,指示最後一次嘗試不成功,使用error事件(請參見下文)並嘗試重新提取文件,直到所有內容都成功加載。

如果你有很多東西要緩存,你可以顯示一個進度條和一些文本,要求用戶在頁面加載時耐心等待。對於進度條,您可以在緩存處理函數的進度事件中使用event.loadedevent.total

var appCache = window.applicationCache; 

// Fired after the first cache of the manifest. 
appCache.addEventListener('cached', handleCacheEvent, false); 

// Checking for an update. Always the first event fired in the sequence. 
appCache.addEventListener('checking', handleCacheEvent, false); 

// An update was found. The browser is fetching resources. 
appCache.addEventListener('downloading', handleCacheEvent, false); 

// The manifest returns 404 or 410, the download failed, 
// or the manifest changed while the download was in progress. 
appCache.addEventListener('error', handleCacheError, false); 

// Fired after the first download of the manifest. 
appCache.addEventListener('noupdate', handleCacheEvent, false); 

// Fired if the manifest file returns a 404 or 410. 
// This results in the application cache being deleted. 
appCache.addEventListener('obsolete', handleCacheEvent, false); 

// Fired for each resource listed in the manifest as it is being fetched. 
appCache.addEventListener('progress', handleCacheEvent, false); 

// Fired when the manifest resources have been newly redownloaded. 
appCache.addEventListener('updateready', handleCacheEvent, false); 

function handleCacheEvent(e){ 
    if(e.type && (e.type=='progress' || e.type=='ProgressEvent')){ 
     console.log('percent:', Math.round(e.loaded/e.total*100)+'%', 'total:', e.total, 'loaded:',e.loaded); 
    } 
} 
+0

這是非常有用的!謝謝! – 2017-05-21 00:12:33

相關問題