World is running under Client Server architecture. In real-time Customer interacts to Server through Clients. Server stores data. Depending upon the level of authentication and type of request Server provides data to Clients. As a common practice in this response request mechanism generally we use Database to store large amount of data. Which resides in Server. During http requests if the page contains data from the Database then it takes time to load. Which directly affects performance. How it is if we can operate large amount of data in Client machine? I can say definitely it will improve the performance.
IndexedDB is a new feature introduced in the 5th revision of HTML. Using IndexedDB we can store large amount of data to the Client Browser. Compare to a Cookie IndexedDB works faster and stores bigger. IndexedDB stores data in KEY & VALUE pair. The term has derived from Database. That’s why by hearing the term “IndexedDB” many of us guess SQL. No it is not like SQL. IndexedDB doesn’t support any kind of SQL query. IndexedDB runs under Single domain only.
Key Concepts of IndexedDB
1. Databases
IndexedDB operates on a per-origin basis, meaning each website or application has its own database. A single origin can have multiple databases, each identified by a unique name.
2. Object Stores
An object store is the primary storage mechanism in IndexedDB, similar to tables in relational databases. Each object store contains a collection of key-value pairs where the key must be unique.
3. Indexes
Indexes allow for efficient querying of data within an object store. They enable developers to retrieve records based on properties other than the primary key.
4. Transactions
Transactions ensure that database operations are performed reliably. A transaction can include multiple read and write operations, and if any operation fails, the entire transaction is rolled back.
5. Cursors
Cursors provide a way to iterate over records in an object store or index, enabling efficient traversal of large datasets.
Getting Started with HTML5 IndexedDB
To implement IndexedDB in a HTML5 page initially you required to declare the following js scripts.
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange if (!window.indexedDB) { window.alert("Update your browser. Older version is incompatible for IndexedDB.") }
Prepare Data for IndexedDB
Before we jump to Create a Database first let us keep some data ready. In below I am presenting few records from my “Employee_Details” table. Keep mark the Data Structure I presented below is in JSON form.
const employeeDetails = [ { emp_id: "01", name: "Raghav Sukla", dob: "01/06/1980", email_id: "raghav@gmail.com" }, { emp_id: "02", name: "Hariharan Swain", dob: "13/11/1972", email_id: "hariharan@gmail.com" } { emp_id: "03", name: "Satyabrata Panda", dob: "22/06/1973", email_id: "satyabrata@gmail.com" } ];
Create an IndexedDB Database
Like we do in SQL or any DBMS here also we required to Create a Database. Look at the below Code here I created a Database. The method I used is “window.indexedDB.open(“<Your Database Name>”). Under Database I handing 3 events onerror for error handling, onsuccess for successful response and onupgradeneeded for adding record during up-gradation.
var mydb; var request = window.indexedDB.open("demoDb", 1); /* Handling Error */ request.onerror = function(event) { console.log("Error Occurred."); }; /* Executing after Success */ request.onsuccess = function(event) { mydb = request.result; console.log("success: "+ mydb); }; /* While Updating */ request.onupgradeneeded = function(event) { var mydb = event.target.result; var objectStore = mydb.createObjectStore("empDetails", {keyPath: "emp_id"}); for (var i in employeeDetails) { objectStore.add(employeeDetails[i]); } }
How to Store records to HTML5 IndexedDB?
Without records Database is meaningless. Let’s watch the example below.
function insertRecords() { var request = mydb.transaction(["empDetails"], "readwrite") .objectStore("empDetails") .add({ emp_id: "04", name: "Vratika Viswakarma", dob: "02/08/1982", email_id: "vratika@gmail.com" }); request.onsuccess = function(event) { alert("Vratika Viswakarma is added to your Database."); }; request.onerror = function(event) { alert("Getting Errors."); } }
While adding records I am maintaining the same sequence and key value pairs.
Function to Read Data from HTML5 IndexedDB
You must aware of the power of a SQL SELECT Statement. Like the same look at the below code how I am fetching records from IndexedDB. Here I used “emp_id” as the WHERE Condition.
function readRecords() { var trans = mydb.transaction(["empDetails"]); var objectStore = trans.objectStore("empDetails"); var request = objectStore.get("04"); /* On Error */ request.onerror = function(event) { alert("Unable to Retrieve Data."); }; /* On Success */ request.onsuccess = function(event) { // Here you can Operate request.result Data! if(request.result) { alert("Name: " + request.result.name + ", DOB: " + request.result.dob + ", Email: " + request.result.email_id); } else { alert("Vratika Viswakarma couldn't be found in your database!"); } }; }
In below this an another way to fetch records sequentially. You can say this trick is similar to a SQL Cursor.
function readAllRecords() { var objectStore = mydb.transaction("empDetails").objectStore("empDetails"); objectStore.openCursor().onsuccess = function(event) { var indexeddb_cursor = event.target.result; if (indexeddb_cursor) { alert("Name for id " + indexeddb_cursor.key + " is " + indexeddb_cursor.value.name + ", DOB: " + indexeddb_cursor.value.dob + ", Email: " + indexeddb_cursor.value.email_id); indexeddb_cursor.continue(); } else { alert("No more entries!"); } }; }
How to Delete records from HTML5 IndexedDB?
Delete is a very Common Operation of DBMS. In the below example we are passing “emp_id” to Delete a record.
function deleteRecords() { var request = mydb.transaction(["empDetails"], "readwrite") .objectStore("empDetails") .delete("04"); request.onsuccess = function(event) { alert("Vratika Viswakarma record has been removed from Database."); }; }
Best Practices
1. Error Handling: Always implement error handling to manage database operation failures gracefully.
2. Transaction Management: Use transactions efficiently to avoid performance bottlenecks.
3. Database Versioning: Handle database upgrades carefully to prevent data loss.
4. Memory Management: Close database connections when not in use to free up resources.
Limitations of IndexedDB
Despite its advantages, IndexedDB has some limitations:
– Complex API: The API is more complex compared to localStorage or sessionStorage.
– Browser Support Variations: While widely supported, some older browsers may have partial or inconsistent implementations.
– No Built-in Synchronization: Unlike server-side databases, IndexedDB does not provide built-in synchronization mechanisms.
Conclusion
HTML5 IndexedDB is a powerful client-side storage solution for web applications requiring large-scale, structured data storage. Its asynchronous nature, transaction support, and indexing capabilities make it ideal for complex applications. While it has a steeper learning curve compared to simpler storage options, mastering IndexedDB enables developers to build more robust and efficient web applications. By following best practices and understanding its core concepts, developers can leverage IndexedDB to enhance user experiences with offline capabilities and fast data access.