現代的瀏覽器已提供了許多客戶端儲存方式。例如早期的cookie或HTML5後的web storage。然而這兩者都無法儲存大量資料。因此這就造成另一個客戶端儲存方式 – IndexedDB脫穎而出。IndexedDB就像非關聯式資料庫(NoSql),每一個app就有一個專屬的資料庫,裡面包含一些表。因此IndexedDB可儲存非結構化資料。它可以是非同步的,而每個存儲動作就像是關聯資料庫裡的transaction(交易)。只要在存儲中有任何一動作失敗,則整筆交易就會失敗。本篇會先介紹IndexedDB的生命週期和資料的CRUD,接者會介紹較進階的項目如Index, Cursor和Range。
IndexedDB的life cycle

由上圖我們知道首先網頁請求(Request)發生,接者瀏覽端IndexedDB程式碼將開始執行。首先判斷是否有新的版本,若有則執行IndexedDB升級動作,例如修改該表的schema或新增資料。若執行成功則繼續執行,若失敗則整個transaction(交易)停止和執行該request onerror這部分的程式碼。
IndexedDB的Initialization 和CRUD

首先

這行會啟動indexedDB,此app的資料庫叫testDB,版本為1。

接者會執行上圖upgrade部分(只有第一次開,版本一初始化時)。上圖會建一個表(名叫users)。上圖在upgrade時,會新增兩筆資料。

若該request執行成功則會執行圖上動作。

首先會先取users表,且模式為readwrite。也可以是readonly。

上圖也是讀取users表的資料

若讀取primary key為1的資料成功,則顯示該資料的name欄位


桉F12到Application這邊,則可以看到該視窗的IndexDB資訊

新增


讀取

修改


刪除


Index,Cursor和Range
Index


上圖宣告index後,我們就可以用age欄位來查詢數據
Cursor和Range

先初始化Cursor

記的最後一定要加上這個code

這樣才會跑完所有資料。

Range
Range要先初始化cursor才能獲得資料

lowerBound(35,false)
該行意思為大於或等於35。第一參數為age,第二為是否包含35。True為不包含,False為包含


小於或等於35


25到30歲之間,包含25和30歲

只等於35歲

本篇介紹了IndexedDB的生命週期,如何增刪改查和說明一些較進階的api操作如Index, Cursor和Range。IndexedDB提供了豐富的API操作,尤其在網路離線時搭配IndexedDB可增加用戶體驗。適當的使用IndexedDB不只在網路端,在移動端也可以協助增加用戶體驗。