IndexedDB是浏览器内置的nosql数据库,支持异步操作、事务处理和大容量存储,可用于缓存复杂数据。通过open()创建或打开数据库,在onupgradeneeded中定义对象存储,使用事务进行增删改查,适合离线应用和接口数据缓存,结合idb库可简化开发。

javaScript 中的本地缓存可以通过多种方式实现,其中 IndexedDB 是最强大、最灵活的一种。它允许你在用户浏览器中存储大量结构化数据,包括文件和二进制数据(Blob),非常适合需要离线功能或高性能本地存储的应用场景。
什么是 IndexedDB?
IndexedDB 是一个浏览器内置的 NoSQL 类型数据库,支持事务处理、索引查询和异步操作。与 localStorage 相比,它能存储更复杂的数据类型,并且容量更大(通常可达几百 MB 甚至更多,具体取决于浏览器)。
它的核心特点包括:
打开并初始化数据库
使用 IndexedDB 第一步是打开数据库连接。如果数据库不存在,会自动创建。
立即学习“Java免费学习笔记(深入)”;
const dbName = "MyCacheDB"; const version = 1; let db; <p>const request = indexedDB.open(dbName, version);</p><p>request.onerror = (event) => { console.error("无法打开 IndexedDB", event.target.error); };</p><p>request.onsuccess = (event) => { db = event.target.result; console.log("数据库打开成功"); };</p><p>request.onupgradeneeded = (event) => { db = event.target.result;</p><p>// 创建一个对象存储(类似表) if (!db.objectStoreNames.contains("cache")) { const objectStore = db.createObjectStore("cache", { keyPath: "id" }); objectStore.createIndex("timestamp", "timestamp", { unique: false }); console.log("对象存储创建完成"); } };</p>
说明:
-
open()返回一个请求对象,用于监听结果 -
onupgradeneeded在数据库首次创建或版本升级时触发,适合定义数据结构 -
keyPath: "id"表示每条记录必须有一个名为id的属性作为主键
增删改查基本操作
所有操作都需在事务中进行。以下是常见 CRUD 操作示例。
添加/更新数据
function putData(id, value) { const transaction = db.transaction(["cache"], "readwrite"); const store = transaction.objectStore("cache"); <p>const data = { id: id, value: value, timestamp: Date.now() };</p><p>const request = store.put(data);</p> <div class="aritcle_card"> <a class="aritcle_card_img" href="/ai/1101"> <img src="https://img.php.cn/upload/ai_manual/001/503/042/68b6c6af75d71275.png" alt="腾讯智影-AI数字人"> </a> <div class="aritcle_card_info"> <a href="/ai/1101">腾讯智影-AI数字人</a> <p>基于AI数字人能力,实现7*24小时AI数字人直播带货,低成本实现直播业务快速增增,全天智能在线直播</p> <div class=""> <img src="/static/images/card_xiazai.png" alt="腾讯智影-AI数字人"> <span>73</span> </div> </div> <a href="/ai/1101" class="aritcle_card_btn"> <span>查看详情</span> <img src="/static/images/cardxiayige-3.png" alt="腾讯智影-AI数字人"> </a> </div> <p>request.onsuccess = () => { console.log("数据保存成功"); };</p><p>request.onerror = () => { console.error("保存失败", request.error); }; }</p>
读取数据
function getData(id) { const transaction = db.transaction(["cache"], "readonly"); const store = transaction.objectStore("cache"); <p>const request = store.get(id);</p><p>request.onsuccess = () => { if (request.result) { console.log("获取数据:", request.result.value); } else { console.log("未找到该 ID 的数据"); } }; }</p>
删除数据
function deleteData(id) { const transaction = db.transaction(["cache"], "readwrite"); const store = transaction.objectStore("cache"); <p>const request = store.delete(id);</p><p>request.onsuccess = () => { console.log("数据已删除"); }; }</p>
遍历所有数据
function getAllData() { const transaction = db.transaction(["cache"], "readonly"); const store = transaction.objectStore("cache"); <p>const request = store.getAll();</p><p>request.onsuccess = () => { console.log("所有缓存数据:", request.result); }; }</p>
实际应用场景:缓存接口数据
可以利用 IndexedDB 缓存 ajax 请求结果,提升页面加载速度。
async function getCachedOrFetch(url) { // 先查缓存 const transaction = db.transaction(["cache"], "readonly"); const store = transaction.objectStore("cache"); const req = store.get(url); <p>return new Promise((resolve, reject) => { req.onsuccess = async () => { const cached = req.result; const cacheAge = cached ? Date.now() - cached.timestamp : Infinity;</p><pre class='brush:php;toolbar:false;'> // 缓存有效时间设为 5 分钟 if (cached && cacheAge < 5 * 60 * 1000) { resolve(cached.value); } else { // 缓存过期或不存在,重新请求 try { const res = await fetch(url); const data = await res.json(); // 更新缓存 putData(url, data); resolve(data); } catch (err) { reject(err); } } };
}); }
调用方式:
getCachedOrFetch("/api/user") .then(data => console.log(data)) .catch(err => console.error(err));
基本上就这些。掌握 IndexedDB 的关键在于理解其异步性和事务模型。虽然 API 略显繁琐,但配合封装函数或使用如 idb 这类轻量库后,开发体验会大幅提升。