IndexedDB

        Modern browser provides many client-side storage options. For example, the early times’ cookie or web storage which came out after HTML5. Nevertheless, none of these two methods can store large amount of data. This results in one another client-side storage method becoming essential in some conditions – that is IndexedDB. IndexedDB is like NoSql, every app has only a database and this database can contain many tables. They can be asynchronous. Every storage action is like relational-database’s transaction. If any procedure in storing action fails, then the whole entire action fails. This article will introduce IndexedDB’s lifecycle, CRUD and some advanced topic- Index, Cursor and Range.

                        IndexedDB life cycle

The above diagram shows that when a request comes, the code related to IndexedDB will execute. The first step is to analysis if there is a new version for the IndexedDB. If yes, it then will conduct upgrade part of IndexedDB, for example, we can change data schema or insert new data. If the process continues to success, it will perform onsuccess code. However, if there is a failure occurs then the wholetransaction process will stop and execute onerror event of code.

IndexedDB Initialization And CRUD

Firstly

This will initialize indexedDB. This app’s database is called testDB and the version is 1.

Then it will execute onupgradeneeded part(this will execute only for the first time when the version 1 open). Then it will create a new table called users and inserts two new data.

If the request successes, it will execute the code above.

It will get the table users firstly, the mode can be readwrite or readonly.

Get users table.

If the primary key is 1 and the request successes, then the webpage will show its name field.

Press F12 and moves to Application, you can get this webpage’s indexedDB information.

Create

Read

Update

Delete

Index, Cursor And Range

Index

The diagram shown above initialize index, so we can query the table by age field.

Cursor And Range

Initialize Cursor first

Remember to add this code

So it will loop all the data

Range

To get the range of data you have to initialize cursor first

lowerBound(35,false)

this code means we will get the users’ data which age is above or equals to 35. The first parameter means age. The second parameter is to decide whether the query includes 35 or not. False means include, true means not include.

Less than or equals to 35.

The age is between 25 and 30. This includes 25 and 30.

Only equals to 35.

This article introduces IndexedDB’s life cycle, how to CRUD and explains some detailed topics Index, Cursor and Range. IndexedDB provides rich Api. Especially when the internet is under offline condition, utilizing IndexedDB will enhance users’ experience. Therefore, appropriate use of Indexed not only in the web but also in the mobile-device will enhance user’s experience.