Web离线存储的几种方式

随着HTML5的正式定稿,我们也可以大量使用HTML离线网络应用程序的特性。

#1、Application Cache

Application Cache 可以很简单让我们的WebApp具有离线的能力。

支持的浏览器:IE10+,FireFox,Chrome,Safari,Opera

优点:

  1. 离线浏览 -- 用户可以再离线时使用Application
  2. 速度 -- 由于缓存了资源,如果加载很快
  3. 减少服务端数据加载 -- 浏览器只需要从服务器加载更新过的数据

缺点:

  1. Manifest文件有变化时才更新
  2. 一次必须更新Manifest中的所有文件,下次才生效

如何使用?

Step1:在html上指定manifest文件 (index.html)

<html manifest="appCacheList.manifest">
</html>

Step2:设定manifest文件内容 (appCache.manifest)

CACHE MANIFEST

# 离线缓存的内容
./all.css
./1.jpg
./index.js # NETWORK:*,表示其他内容从网络获取
NETWORK:
* # 第一个uri是资源,第二个是fallback
FALLBACK:
/html/ /offline.html

手动更新缓存:

if ( window.applicationCache.status == window.applicationCache.UPDATEREADY ){
window.applicationCache.update();
}

注意:

  1. 不同的浏览器对Application Cache的大小不一致,请注意。
  2. 更多细节可参考http://kayosite.com/web-app-by-jquery-mobile-and-html5-offline-web-applications.html

#2、Local Storage

Local Storage使得我们可以在浏览器中保存数据。

支持的浏览器:IE10+,FireFox,Chrome,Safari,Opera

优点:

  1. 容量大
  2. 易用
  3. 强大
  4. 原生支持
  5. 仅存在本地,不会与服务器发生交互

缺点:

  1. 浏览器兼容性差
  2. 安全性差(不要存储敏感数据)

如何使用?

首先通过 window.localStorage 来判断浏览器是否支持Local Storage。然后由于该方式具有浏览器兼容性,建议用一个通用的库,来屏蔽兼容性。

// 对基本方法的封装,需要判断浏览器,屏蔽它们的细节差异。
(function(window){
if(!window.localStorage){
throw new Error('Your brower can\'t support local storage!');
}
var ls = window.localStorage;
var localStorageKit = {
getLength: function(){
return ls.length;
},
clear: function(){
ls.clear();
return true;
},
set: function(k, v){
ls.setItem(k, v);
},
get: function(k){
return ls.getItem(k);
},
remove: function(k){
ls.removeItem(k);
},
getKeyByIndex: function(index){
return ls.key(index);
}
};
window.lsKit = localStorageKit;
})(window);

基本操作方式与cookie无太多差异。

Session Storage: Session Storage和Local Storage非常类似,操作方式也一致。由于其中保存的存只是当前会话有效,那么此处就不细说。

#3、Web SQL

Web Sql Database,是html5环境下可以用js执行CRUD的web数据库。数据库核心是SQLite。

优点:

  1. 本地数据库
  2. 可以处理复杂的关系型数据

缺点:

  1. 暂时只有chrome才支持,对于Android大行其道的移动端,这应该是可以避免的缺点(貌似最新版本的Opera和Safari也支持了)

如何使用?

首先,先介绍Web sql的三个核心方法:

  1. openDatabase:这个方法使用现有数据库或创建新数据库创建数据库对象。
  2. transaction:这个方法允许我们根据情况控制事务提交或回滚。
  3. executeSql:这个方法用于执行真实的SQL查询。

    var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")'); console.log('Log message created and row inserted.'); }); db.transaction(function (tx) { tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { var len = results.rows.length, i; console.log('Found rows: ' + len); for (i = 0; i < len; i++){ console.log(results.rows.item(i).log) } }, null); });

当成数据库用,就行。

#4、IndexedDB

IndexedDB是结构化的本地数据存储。是基于平面文件的数据库,采用了分层的键值存储和基本的索引。

优点:

  1. 标准化
  2. 存储复杂数据
  3. 支持索引

缺点:

  1. 不支持SQL
  2. 相对来说,操作较复杂

如何使用?

// 打开数据库,第一个参数为数据库名,第二个为数据库版本号
var dbRequest = window.indexedDB.open('testDb', 2); dbRequest.onupgradeneeded=function(e){
// 创建数据仓库
var db=e.target.result;
if(!db.objectStoreNames.contains('users')){
var store=db.createObjectStore('users',{keyPath: 'id'});
store.createIndex('nameIndex','name',{unique:true});
store.createIndex('ageIndex','age',{unique:false});
}
console.log('upgrade successfully!');
}; dbRequest.onsuccess = function(e){
console.log('Open database successfully!');
// 这里拿到了数据库
var db = e.target.result;
var storeName = 'users';
// 写入数据
var tran = db.transaction(storeName, 'readwrite');
var users = tran.objectStore(storeName);
for(var i = 0; i < 5; i++){
users.add({
id: i,
name: 'user' + i,
age: Math.floor(Math.random() * 10) + 18
});
} //查询数据
var userStore = db.transaction(storeName).objectStore(storeName);
var request = userStore.openCursor();
request.onsuccess = function(e){
var cursor = e.target.result;
if(cursor){
console.log(cursor.key);
console.log(cursor.value);
cursor.continue();
}
}
}

其他

HTML 5中几种用于在客户端本地存储数据的API之间的比较

HTML5本地存储——IndexedDB(一:基本使用)

HTML5本地存储——IndexedDB(二:索引)

*:first-child {
margin-top: 0 !important;
}

body>*:last-child {
margin-bottom: 0 !important;
}

/* BLOCKS
=============================================================================*/

p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}

/* HEADERS
=============================================================================*/

h1, h2, h3, h4, h5, h6 {
margin: 20px 0 10px;
padding: 0;
font-weight: bold;
-webkit-font-smoothing: antialiased;
}

h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
font-size: inherit;
}

h1 {
font-size: 28px;
color: #000;
}

h2 {
font-size: 24px;
border-bottom: 1px solid #ccc;
color: #000;
}

h3 {
font-size: 18px;
}

h4 {
font-size: 16px;
}

h5 {
font-size: 14px;
}

h6 {
color: #777;
font-size: 14px;
}

body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}

a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}

h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}

/* LINKS
=============================================================================*/

a {
color: #4183C4;
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

/* LISTS
=============================================================================*/

ul, ol {
padding-left: 30px;
}

ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}

ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}

dl {
padding: 0;
}

dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}

dl dt:first-child {
padding: 0;
}

dl dt>:first-child {
margin-top: 0px;
}

dl dt>:last-child {
margin-bottom: 0px;
}

dl dd {
margin: 0 0 15px;
padding: 0 15px;
}

dl dd>:first-child {
margin-top: 0px;
}

dl dd>:last-child {
margin-bottom: 0px;
}

/* CODE
=============================================================================*/

pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}

code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}

pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}

pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}

pre code, pre tt {
background-color: transparent;
border: none;
}

kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}

/* QUOTES
=============================================================================*/

blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}

blockquote>:first-child {
margin-top: 0px;
}

blockquote>:last-child {
margin-bottom: 0px;
}

/* HORIZONTAL RULES
=============================================================================*/

hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}

/* IMAGES
=============================================================================*/

img {
max-width: 100%
}
-->

上一篇:Winform中使用printDocument控件打印pictureBox中的二维码照片


下一篇:mark win to linux winscp