h5的离线缓存机制

什么是Manifest:

其实Manifest是一个简单的 文本文件,它的扩展名是任意的,定义需要缓存的文件、资源,当第一次打开时,浏览器会自动缓存相应的资源。

 

Manifest 的特点:

  • 离线浏览:即当网络断开时,可以继续访问你的页面。
  • 访问速度快:将文件缓存到本地,不需每次都从网络上请求。
  • 稳定性:做了Manifest缓存,遇到突发网络故障或者服务器故障,继续访问本地缓存。

 

Manifest的使用:

html新增了一个manifest属性,可以用来指定当前页面的manifest文件。

创建一个和html同名的manifest文件,比如页面为index.html,那么可以建一个index.manifest的文件,然后给index.html的html标签添加如下属性即可:

<html lang="en" manifest="index.manifest"> 或<html manifest="http://www.example.com/index.manifest">

1、manifest 的引入可以使绝对路径也可以是相对路径,如果你使用的是绝对路径,你的manifest文件必须和你的站点挂在同一个域名下。

2、manifest文件你可以保存为任意的扩展名,但mine-type 必须是 text/cache-manifest。

<html lang="en" manifest="index.manifest">  或  <html lang="en" manifest="index.cache"> 在服务器上部署时需要在服务器上添加相应的mie-type

3、manifest 标签应该包含到你需要缓存资源的页面,当第一次打开该页面时,浏览器会解析该页面中的mainfest,并缓存里面列举的资源,同时该页面也会自动会被浏览器缓存,即使该页面没有在Manifest中列出。

Manifest文件结构:

接下来详细说说manifest的细节,一个典型的manifest文件代码结构像下面这样:

CACHE MANIFEST(必在第一行,必须写)

# version 2016-01-01  10:10

CHCHE:(必须写)

#缓存文件

NETWORK:

#不缓存文件

FALLBACK:

#页面无法访问时的回退页

 

方法:

update():检测更新manifest文件

updateready事件:当有新的缓存,并更新完之后,会触发此事件

swapCache(): 用来执行本地缓存的更新操作触发updateready事件时调用

window.applicationCache.update();
        window.applicationCache.addEventListener("updateready", function(e) {
                window.applicationCache.swapCache();
                if (confirm("A new version of this site is available. Load it?")) {
                    window.location.reload();
                }

}, false);

progress事件:当有新的缓存,并处于正在下载的过程中时会不断出发此事件

window.applicationCache.addEventListener("progress",function(){
            alert(window.applicationCache.status);   //0未缓存    1空闲     2检查中     3下载中     4更新就绪      5缓存过期

});

checking事件:正在检查

noupdate事件:检查更新结束,没有需要更新。

downloading事件:正在下载

cached事件:空闲,缓存为最新状态

error事件:报错

posted @ 2016-10-24 19:54  蒙张开翅膀  Views(1440)  Comments(0Edit  收藏  举报