WebApp本地存储 (离线缓存策略策略)
开发离线应用的缓存方法大概有4种(如下safari开发工具中的resources所示)
1.cookies(略):传统储存策略。缺点很明显:储存的容量过小,而且很容易被各种软件当垃圾清除,如360等。
2.Application Cache资源缓存:在html中指定一个manifest文件,给文件中罗列出需要缓存的资源文件列表。浏览器根据资源列表对资源文件缓存。
3.Dom Storage:这一种基于key/value的格式。
DOM Storage 分为两类:sessionStorage 和 localStorage。除了以下区别外,这两类存储对象的功能是完全一致的。
- sessionStorage 用于存储与当前浏览器窗口关联的数据。窗口关闭后,sessionStorage 中存储的数据将无法使用。
- localStorage 用于长期存储数据。窗口关闭后,localStorage 中的数据仍然可以被访问。所有浏览器窗口可以共享 localStorage 的数据.
示例:(这才是重点啊!) 目前我只尝试过Application Cache,所以也只给出这个例子。 开发环境:Apache+php+(windows下的safari,chrome,firefox)/ipod touch下的safari 目的:缓存我指定的index.html和其中的jquery.js资源文件。index.html中的图片不缓存。 文件目录分布如下: /jqueryapp/ --------------------------------------------- 1.index.html 2.jquery.js 3.tetris.php(可能大家觉得这个文件很奇怪,其实是用来发送manifest的mime type的。不然就要修改apache的mime.types或者用.htaccess,很多人没有这个条件,比如我) 4.tetris.manifest --------------------------------------------- index.html代码 [plain] view plaincopy
- <!DOCTYPE html>
- <html manifest="tetris.php">
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
- <meta name="apple-mobile-web-app-capable" content="yes" />
- <meta name="apple-mobile-web-app-status-bar-style" content="black" />
- <link rel="apple-touch-icon" href="iphon_tetris_icon.png"/>
- <link rel="apple-touch-startup-image" href="startup.png" />
- <title>appdig</title>
- <script src="jquery.js"></script>
- <span style="white-space:pre"> </span><style type="text/css">
- <span style="white-space:pre"> </span>body,div,ul,li,p,span,img{
- <span style="white-space:pre"> </span>margin:0px;
- <span style="white-space:pre"> </span>padding:0px;
- <span style="white-space:pre"> </span>}……
[plain] view plaincopy
- <?php
- header("Content-Type: text/cache-manifest");
- readfile("tetris.manifest");
[plain] view plaincopy
- CACHE MANIFEST
- index.html
- jquery.js
后记:关于manifest的mime type声明 html5提供的这种方法必须保证<html manifest="文本文件">中的文本文件(任意名字和任意扩展名)是text/cache-manifest类型的。即其header必须声明其类型是text/cache-manifest的。
其实如果你有修改apache服务器或者别的web服务器的权限你完全可以不用tetris.php这个文件。在index.html中的直接用 <html manifest="tetris.manifest">就可以。 修改apache的mime.types配置文件,在其中加上下面这句。
text/cache-manifest manifest或者用.htaccess,加添下面那句(我没尝试)。 AddType text/cache-manifest用我上面的方法的好处就是不用修改和添加任何配置文件。利用php来发送header来告诉浏览器我是text/cache-manifest类型的。 参考资料: 1.http://www.ibm.com/developerworks/cn/web/1011_guozb_html5off/ 非常的详细讲解了离线应用的储存策略 2.http://www.qianduan.net/local-storage-of-html5.html 3.http://www.yiiyaa.net/1414 详细讲了manifest的用法 4.http://www.zzbaike.com/wiki/Htaccess 讲了.htaccess的用法
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。