构建一个使用 IndexedDB 作为后端、支持离线搜索的渐进式 Web 应用(PWA)需整合服务 Worker、IndexedDB、前端搜索逻辑与 Web App Manifest,核心步骤如下:
1. 注册服务 Worker 实现离线缓存服务 Worker 是 PWA 离线能力的核心,需缓存静态资源(HTML、CSS、JS)及动态数据。
- 注册服务 Worker:在主页面中检测浏览器支持性并注册:if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(reg => console.log('SW registered:', reg)) .catch(err => console.error('SW registration failed:', err));}
- 缓存资源:在 sw.js 中定义缓存版本与资源列表,拦截 fetch 事件优先返回缓存内容:const CACHE_NAME = 'pwa-search-v1';const urlsToCache = ['/', '/index.html', '/styles.css', '/app.js', '/idb.js'];self.addEventListener('install', event => { event.waitUntil( caches.open(CACHE_NAME).then(cache => cache.addAll(urlsToCache)) );});self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request).then(response => response || fetch(event.request) ) );});
2. 使用 IndexedDB 存储数据并实现本地搜索IndexedDB 是异步、事务型数据库,适合存储结构化数据。推荐使用 idb 库简化操作。
- 初始化数据库:创建数据库与对象存储(Object Store),并定义索引以加速搜索:import { openDB } from 'idb';const initDB = async () => { return openDB('SearchApp', 1, { upgrade(db) { if (!db.objectStoreNames.contains('items')) { const store = db.createObjectStore('items', { keyPath: 'id' }); store.createIndex('title', 'title'); store.createIndex('content', 'content'); } } });};
- 预加载数据:首次加载时从远程 API 获取数据并存入 IndexedDB:const loadAndStoreData = async () => { const db = await initDB(); const res = await fetch('/api/data'); const items = await res.json(); const tx = db.transaction('items', 'readwrite'); items.forEach(item => tx.store.put(item)); await tx.done;};
- 实现离线搜索:通过索引查询标题或内容字段,合并结果并去重:const searchLocal = async (query) => { const db = await initDB(); const titleIndex = db.transaction('items').objectStore('items').index('title'); const contentIndex = db.transaction('items').objectStore('items').index('content'); const titleResults = await titleIndex.getAll(IDBKeyRange.bound( query.toLowerCase(), query.toUpperCase() + 'uffff' )); const contentResults = await contentIndex.getAll(IDBKeyRange.bound( query.toLowerCase(), query.toUpperCase() + 'uffff' )); const map = new Map(); [...titleResults, ...contentResults].forEach(item => { map.set(item.id, item); }); return Array.from(map.values());};
3. 前端集成搜索界面与状态提示- 搜索输入框与结果展示:绑定输入事件,实时调用本地搜索并渲染结果:<input type="text" id="searchInput" placeholder="搜索内容..."><div id="results"></div><script> document.getElementById('searchInput').addEventListener('input', async (e) => { const query = e.target.value.trim(); if (query.length < 2) { document.getElementById('results').innerHTML = ''; return; } const results = await searchLocal(query); const resultsEl = document.getElementById('results'); resultsEl.innerHTML = results.map(item => `<div><h3>${item.title}</h3><p>${item.content}</p></div>` ).join(''); });</script>
- 网络状态检测:监听 online/offline 事件,更新 UI 提示用户当前模式:window.addEventListener('online', updateStatus);window.addEventListener('offline', updateStatus);function updateStatus() { console.log(navigator.onLine ? '在线' : '离线'); // 可更新 UI 显示“当前为离线模式”}
4. 添加 Web App Manifest 实现可安装性创建 manifest.json 文件定义应用元数据,使浏览器识别为 PWA 并支持安装:
{ "name": "离线搜索应用", "short_name": "SearchApp", "start_url": "/", "display": "standalone", "background_color": "#ffffff", "theme_color": "#000000", "icons": [ { "src": "icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icon-512.png", "sizes": "512x512", "type": "image/png" } ]}在 HTML 中引用:
<link rel="manifest" href="/manifest.json"><meta name="viewport" content="width=device-width, initial-scale=1">关键注意事项- 缓存策略:服务 Worker 的缓存需定期更新(如版本升级时清除旧缓存)。
- 索引设计:根据搜索需求优化索引字段(如全文搜索需分词处理)。
- 数据同步:网络恢复后,可将本地修改同步至远程服务器。
- 性能优化:大数据量时考虑分页加载或虚拟滚动。
通过以上步骤,即可构建一个支持离线搜索、可安装的渐进式 Web 应用,实现“离线优先”的用户体验。