Web離線儲存的幾種方式

來源:互聯網
上載者:User

標籤:

 

隨著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是資源,第二個是fallbackFALLBACK:/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是結構化的本機資料儲存。是基於一般檔案的資料庫,採用了分層的KVStore for Redis和基本的索引。

優點:

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

 

Web離線儲存的幾種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.