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(二:索引)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM