In modern web applications, local storage is a key technology for implementing offline functionality and improving user experience. As web applications become more complex, developers need to understand the various local storage solutions provided by browsers to choose the most appropriate storage method for different scenarios.
I. Overview of Browser Local Storage Solutions
Browsers provide multiple local storage solutions, each with its applicable scenarios and limitations:
| Storage Solution | Storage Capacity | Data Type | Persistent | Main Usage |
|---|---|---|---|---|
| localStorage | 5MB | String | Yes | User preferences, session data |
| sessionStorage | 5MB | String | No | Temporary session data |
| IndexedDB | Unlimited | Structured data | Yes | Offline data, large data storage |
| Cache API | Unlimited | HTTP request/response | Yes | Offline caching, resource caching |
II. localStorage: Simple Key-Value Storage
localStorage is the simplest local storage solution, providing key-value pair storage where data persists after page refresh.
Basic Usage
// Store data
localStorage.setItem('username', 'Zhang San');
localStorage.setItem('settings', JSON.stringify({ darkMode: true, fontSize: 16 }));
// Read data
const username = localStorage.getItem('username');
const settings = JSON.parse(localStorage.getItem('settings'));
// Remove data
localStorage.removeItem('username');
// Clear all data
localStorage.clear();
// Get all keys
const keys = Object.keys(localStorage);
Applicable Scenarios
- User preferences (theme, font size, etc.)
- Simple user session data
- Form auto-fill data
- Application configuration parameters
Notes
- Only supports string type, complex data requires
JSON.stringify()andJSON.parse() - Storage capacity is approximately 5MB, exceeding will throw an exception
- Data is sent with HTTP requests (may cause security issues)
- Synchronous operations, large amounts of data will block the main thread
III. sessionStorage: Temporary Session Storage
sessionStorage has the same API as localStorage, but data is only valid for the current session and will be cleared after closing the browser tab.
Basic Usage
// Store session data
sessionStorage.setItem('currentPage', '/dashboard');
// Read data
const currentPage = sessionStorage.getItem('currentPage');
// Auto-cleared after session ends
Applicable Scenarios
- Temporary form data (prevent loss on refresh)
- Current page state
- Sensitive data (no persistence needed)
IV. IndexedDB: Large-Scale Structured Storage
IndexedDB is a transactional database system provided by browsers, supporting the storage of large amounts of structured data. It is the core technology for PWA offline applications.
Basic Usage
// Open database
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create object store
const store = db.createObjectStore('users', { keyPath: 'id' });
// Create index
store.createIndex('name', 'name', { unique: false });
};
request.onsuccess = (event) => {
const db = event.target.result;
// Add data
const transaction = db.transaction(['users'], 'readwrite');
const store = transaction.objectStore('users');
store.add({ id: 1, name: 'Zhang San', age: 28 });
transaction.oncomplete = () => {
console.log('Data added successfully');
};
};
Advanced Queries
// Query using index
const transaction = db.transaction(['users'], 'readonly');
const store = transaction.objectStore('users');
const index = store.index('name');
// Get all users named "Zhang San"
const request = index.getAll('Zhang San');
request.onsuccess = (event) => {
const users = event.target.result;
console.log(users);
};
// Range query
const range = IDBKeyRange.bound(20, 30);
const ageRequest = store.index('age').getAll(range);
Applicable Scenarios
- Offline application data storage
- Large amounts of structured data (such as user lists, product data)
- Complex queries requiring index and transaction support
- Binary data storage for images, files, etc.
π‘ Tip:IndexedDB operations are asynchronous and will not block the main thread. It is recommended to use wrapper libraries such as localForage or idb to simplify operations.
V. Cache API: Resource Caching
Cache API is mainly used for caching HTTP requests and responses, which is the key to implementing offline applications with Service Workers.
Basic Usage
// Cache resources in Service Worker
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/styles.css',
'/app.js'
]);
})
);
});
// Intercept requests and return cached responses
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
// Return cached or fetch from network
return response || fetch(event.request);
})
);
});
VI. Best Practice Recommendations
1. Choose Storage Solution Based on Data Type
- Simple key-value pairs, configuration data β
localStorage - Temporary session data β
sessionStorage - Large amounts of structured data β
IndexedDB - Static resource caching β
Cache API
2. Data Serialization
For localStorage and sessionStorage, pay attention to serialization and deserialization when storing complex data:
// Serialize before storing
const data = { name: 'Zhang San', age: 28 };
localStorage.setItem('user', JSON.stringify(data));
// Deserialize after reading
const user = JSON.parse(localStorage.getItem('user'));
3. Error Handling
try {
localStorage.setItem('key', 'value');
} catch (e) {
if (e.name === 'QuotaExceededError') {
console.warn('Storage quota exceeded');
// Clean up old data or notify user
}
}
4. Data Version Management
For IndexedDB, use version numbers to manage database structure changes:
const request = indexedDB.open('myDatabase', 2);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const oldVersion = event.oldVersion;
if (oldVersion < 2) {
// Add new fields or indexes
const store = db.transaction.objectStore('users');
store.createIndex('email', 'email', { unique: true });
}
};
VII. Summary
Choosing the appropriate local storage solution depends on the type, size, and usage scenario of the data:
- localStorage: Simple, synchronous, suitable for small configuration data
- sessionStorage: Temporary storage, suitable for session data
- IndexedDB: Asynchronous, transactional, suitable for large structured data
- Cache API: Resource caching, suitable for offline applications
In actual development, multiple storage solutions are usually combined to give full play to their respective advantages and provide users with better offline experience and performance.