这是预期的浏览器行为吗?
这确实是预期的行为。见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
thewindow.applicationCache.status
是否为checking
或downloading
.
或者您可以在用户 localStorage 中设置一个标志,指示上次尝试未成功,使用error
事件(见下文)并尝试重新获取文件,直到所有内容都成功加载。
如果你有很多东西要缓存,你可以显示一个进度条和一些文本,要求用户在页面加载时耐心等待。对于进度条,您可以在缓存处理函数event.loaded
的event.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);
}
}