使用html5 manifest,开始网页离线应用开发,离线文件一直保存在用户客户端,除非用户手动删除数据
每个指定了 manifest 的页面在用户对其访问时都会被缓存。如果未指定 manifest 属性,则页面不会被缓存(除非在 manifest 文件中直接指定了该页面)。
manifest 文件的建议的文件扩展名是:".appcache"。
请注意,manifest 文件需要配置正确的 MIME-type,即 "text/cache-manifest"。必须在 web 服务器上进行配置。
manifest 文件是简单的文本文件,它告知浏览器被缓存的内容(以及不缓存的内容)。
manifest 文件可分为三个部分:
CACHE MANIFEST - 在此标题下列出的文件将在首次下载后进行缓存
NETWORK - 在此标题下列出的文件需要与服务器的连接,且不会被缓存
FALLBACK - 在此标题下列出的文件规定当页面无法访问时的回退页面(比如 404 页面)
如何使用?
声明
<!DOCTYPE>
<html manifest="/index.manifest">
...
<body onload="CheckManifest();">
2. 编辑manifest文件;注意:与应用相关的所有文件都要在此文件里可匹配到
CACHE MANIFEST
# VERSION 1.0 Testing Code 20140630 16:28
#要离线使用的文件列表
CACHE:
/JS/modernizr.js
/JS/prototype.1.7.1.js
#不需要离线的文件列表,可使用通配符
NETWORK:
/JS/manifest_handling.js
/content/
#google地图服务
http://maps.googleapis.com/maps/api/js?sensor=false
http://maps.gstatic.com/
http://maps.google.com/
http://maps.googleapis.com/
http://mt0.googleapis.com/
http://mt1.googleapis.com/
http://mt2.googleapis.com/
http://mt3.googleapis.com/
http://khm0.googleapis.com/
http://khm1.googleapis.com/
http://cbk0.googleapis.com/
http://cbk1.googleapis.com/
http://www.google-analytics.com/
http://gg.google.com/
http://fonts.googleapis.com/
http://mt0.googleapis.com/
http://csi.gstatic.com/
http://themes.googleusercontent.com/
#替补文件列表,可使用通配符;当前一个路径找不到资源时,使用后一个替补
FALLBACK:
/html5/ /404.html
3. 处理cache监听
/*
http://dev.w3.org/html5/spec-author-view/offline.html#appcacheevents
*/
var iMani_num = 0;
var iMani_Total = 198; /* Total Number of files is 'cache' + 2 (html + manifest) */
function CheckManifest() {
var appCache = window.applicationCache;
//$('manifest_box').show();
if (appCache) {
// First Time cache
appCache.oncached = function() {
$('div_manifest').innerHTML = "<span>All completed.</span>";
$('manifest_box').hide();
};
// Manifest Update
appCache.onupdateready = function() {
if (appCache.status == appCache.UPDATEREADY) {
$('manifest_box').show();
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new version.
appCache.swapCache();
$('div_manifest').innerHTML = "<span style='text-align:center;'>New version is ready, click <a href='javascript:window.location.reload();' style='color:red;'>here</a> to refresh now.</span>";
}
};
// Progress
appCache.onprogress = function() {
// Total Number of files is 'cache' + 2 (html + manifest)
$('manifest_box').show();
iMani_num++;
var iLoaded = Math.round((iMani_num/iMani_Total)*100);
if (iLoaded > 100.0) iLoaded = 100;
$('div_manifest').innerHTML = "<span style='text-align:center;'>Loading... " + iLoaded + "%</span>";
};
}
}