JS如何实现本地缓存_JavaScriptIndexedDB本地数据库使用方法详解

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

JavaScript 中的本地缓存可以通过多种方式实现,其中 IndexedDB 是最强大、最灵活的一种。它允许你在用户浏览器中存储大量结构化数据,包括文件和二进制数据(Blob),非常适合需要离线功能或高性能本地存储的应用场景。

什么是 IndexedDB?

IndexedDB 是一个浏览器内置的 NoSQL 类型数据库,支持事务处理、索引查询和异步操作。与 localStorage 相比,它能存储更复杂的数据类型,并且容量更大(通常可达几百 MB 甚至更多,具体取决于浏览器)。

它的核心特点包括:

  • 异步 API,不会阻塞主线程
  • 支持对象存储(Object Store),可存 JS 对象、数组、日期、Blob 等
  • 支持通过键或索引进行高效查询
  • 基于事务机制,保证数据一致性

打开并初始化数据库

使用 IndexedDB 第一步是打开数据库连接。如果数据库不存在,会自动创建。

const dbName = "MyCacheDB";
const version = 1;
let db;

const request = indexedDB.open(dbName, version);

request.onerror = (event) => { console.error("无法打开 IndexedDB", event.target.error); };

request.onsuccess = (event) => { db = event.target.result; console.log("数据库打开成功"); };

request.onupgradeneeded = (event) => { db = event.target.result;

// 创建一个对象存储(类似表) if (!db.objectStoreNames.contains("cache")) { const objectStore = db.createObjectStore("cache", { keyPath: "id" }); objectStore.createIndex("timestamp", "timestamp", { unique: false }); console.log("对象存储创建完成"); } };

说明:

  • open() 返回一个请求对象,用于监听结果
  • onupgradeneeded 在数据库首次创建或版本升级时触发,适合定义数据结构
  • keyPath: "id" 表示每条记录必须有一个名为 id 的属性作为主键

增删改查基本操作

所有操作都需在事务中进行。以下是常见 CRUD 操作示例。

添加/更新数据

function putData(id, value) {
  const transaction = db.transaction(["cache"], "readwrite");
  const store = transaction.objectStore("cache");

const data = { id: id, value: value, timestamp: Date.now() };

const request = store.put(data);

request.onsuccess = () => { console.log("数据保存成功"); };

request.onerror = () => { console.error("保存失败", request.error); }; }

读取数据

function getData(id) {
  const transaction = db.transaction(["cache"], "readonly");
  const store = transaction.objectStore("cache");

const request = store.get(id);

request.onsuccess = () => { if (request.result) { console.log("获取数据:", request.result.value); } else { console.log("未找到该 ID 的数据"); } }; }

删除数据

function deleteData(id) {
  const transaction = db.transaction(["cache"], "readwrite");
  const store = transaction.objectStore("cache");

const request = store.delete(id);

request.onsuccess = () => { console.log("数据已删除"); }; }

遍历所有数据

function getAllData() {
  const transaction = db.transaction(["cache"], "readonly");
  const store = transaction.objectStore("cache");

const request = store.getAll();

request.onsuccess = () => { console.log("所有缓存数据:", request.result); }; }

实际应用场景:缓存接口数据

可以利用 IndexedDB 缓存 AJAX 请求结果,提升页面加载速度。

async function getCachedOrFetch(url) {
  // 先查缓存
  const transaction = db.transaction(["cache"], "readonly");
  const store = transaction.objectStore("cache");
  const req = store.get(url);

return new Promise((resolve, reject) => { req.onsuccess = async () => { const cached = req.result; const cacheAge = cached ? Date.now() - cached.timestamp : Infinity;

  // 缓存有效时间设为 5 分钟
  if (cached && cacheAge zuojiankuohaophpcn 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 这类轻量库后,开发体验会大幅提升。