h5的离线缓存机制

什么是Manifest:html

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

 

Manifest 的特色:缓存

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

 

Manifest的使用:服务器

html新增了一个manifest属性,能够用来指定当前页面的manifest文件。网络

建立一个和html同名的manifest文件,好比页面为index.html,那么能够建一个index.manifest的文件,而后给index.html的html标签添加以下属性便可:app

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

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

二、manifest文件你能够保存为任意的扩展名,但mine-type 必须是 text/cache-manifest。code

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

三、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事件:报错

相关文章
相关标签/搜索