HTML5 离线缓存DEMO示例
来源:互联网 发布:c 多核高级编程 编辑:程序博客网 时间:2024/06/16 03:53
1.index.manifest文件配置
- CACHE MANIFEST
- #chrome浏览器支持,火狐浏览器支持度不够好
- #version 1
- #author by guoquanyou
-
- #CACHE:其后列出的是需要缓存的内容
- CACHE:
- index.html
- css/index.css
- img/girl.jpg
-
- #NETWORK:其后列出的是不进行缓存的内容,每次都需要从服务器端获取
- NETWORK:
- *
-
- FALLBACK:
-
- img/pirate1.png img/pirate_back.png
2.index.html- <!DOCTYPE html>
- <html manifest="index.manifest">
- <head>
- <meta charset="utf-8" />
- <title></title>
- <link rel="stylesheet" href="css/index.css" />
- <script type="text/javascript">
- //判断浏览器是否能够连接互联网,online表示能够联网,offline表示不能联网;根据浏览器状态自动监听并进行响应【通过断开或开启本地连接进行测试】
- window.addEventListener("online", function() {
- alert("您已变成在线状态")
- }, true);
- window.addEventListener("offline", function() {
- alert("您已变成离线状态")
- }, true);
- //手动判断浏览器的联网状态
- /* if(navigator.onLine){
- alert("在线");
- }else{
- alert("离线");
- } */
- //alert("navigator.onLine:"+navigator.onLine);
- //当index.manifest内容更新时,浏览器检查到存在更新,并进行提示
- function init() {
- setInterval("toUpdateCache()", 3000);
- }
- function toUpdateCache() {
- //强制检查服务器上的manifest文件是否有更新
- applicationCache.update();
- }
- applicationCache.onupdateready = function() {
- if (confirm("本地缓存已被更新,需要刷新页面来获取应用程序最新版本")) {
- //手动更新本地缓存,只能在onupdateready事件触发时调用
- applicationCache.swapCache();
- location.reload();
- }
- }
- //与上述写法完全等效
- /* applicationCache.addEventListener("updateready",function(){
- if(confirm("本地缓存已被更新,需要刷新页面来获取应用程序最新版本")){
- //手动更新本地缓存,只能在onupdateready事件触发时调用
- applicationCache.swapCache();
- location.reload();
- }
- },true); */
-
- /* function test(){
- var msg=document.getElementById("msg");
- applicationCache.onchecking=function(){
- msg.innerHTML+="onchecking<br/>";
- }
- applicationCache.ondownloading=function(){
- msg.innerHTML+="ondownloading<br/>";
- }
- applicationCache.onprogress=function(){
- msg.innerHTML+="onprogress<br/>";
- }
- applicationCache.onupdateready=function(){
- msg.innerHTML+="onupdateready<br/>";
- }
- applicationCache.oncached=function(){
- msg.innerHTML+="oncached<br/>";
- }
- applicationCache.onerror=function(){
- msg.innerHTML+="onerror<br/>";
- }
-
- } */
- </script>
- </head>
- <body onload="init()">
- <img src="img/girl.jpg" /><img src="img/pirate1.png" />
- <img src="img/pirate.png" /> 一个来自服务器端的传说。
- <div id="msg"></div>
- </body>
- </html>
3.项目结构
4.使用Tomcat服务器,确认C:\apache-tomcat-8.0.28\conf目录下的web.xml中已经包含以下配置:
- <mime-mapping>
- <extension>appcache</extension>
- <mime-type>text/cache-manifest</mime-type>
- </mime-mapping>
5.运行服务器,并访问index.html页面:1)断开本地连接,然后启用,查看页面的反应情况;
2)修改index.manifest文件,查看页面的反应情况。