Introduction
Indexed DB is a local storage system which stores data in client-side on the browser. This is useful for applications that require storing a large amount of the data. These applications can run more efficiently and can load faster.
Objective
The main objective of this indexed DB is to improve the performance of the page load. It avoids the number of calls to retrieve the data from the database
How Indexed DB works?
- First time when page loads, it calls the data from the database and stores the data in the indexed DB.
- When again calling for the same record, it will load from the indexed DB instead of the load from the database. So, the application can run more efficiently and load faster.
- Since the indexed DB gets updated on every call, it will have the updated data just same as in the database.
- Since it displays the data from the indexed DB and then calls to the database on the page load, the application can improve the load performance.
Things to know before starting with Indexed DB
- To start working with indexed DB, we must check whether our browser supports indexed DB or not.
- We must be aware of the below methods.
- Push the data to indexed DB when data comes from the database for the first time.
- Pull data from the indexed DB when data is already existing in the indexed DB.
- Filter the data based on the requirement.
- Update the indexed DB based on the changes.
Step 1. Check browser compatibility
Check the browser compatibility by running the below code.
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("Your browser doesn't support IndexedDB.")
}
Step 2. If the browser supports the indexed DB, write a code for adding the retrieved data to the indexed DB.
Code for adding the data into indexed DB.
var dbName = "MyDB";
var request = indexedDB.open(dbName);
request.onerror = function(event) {
// Handle errors.
};
request.onupgradeneeded = function(event) {
db = event.target.result;
objectStore = db.createObjectStore("Discussions", {
keyPath: "ID"
});
objectStore.createIndex("ID", "ID", {
unique: false
});
objectStore.transaction.oncomplete = function(event) {
customerObjectStore = db.transaction("Discussions", "readwrite").objectStore("Discussions");
for (var i in customerData) { /* where the customerData is our retrieved Data*/
customerObjectStore.add(customerData[i]);
}
};
}; 
Hadshana KamalanathanPosted Jul 14, 2018, 1:39 AM
Thanks for sharing
Dharmraj ThakurPosted Dec 5, 2017, 11:57 PM
Nice shared.........................