Appearance
- Mozilla 开发的用于改善 web app 的离线体验的 JS 库
- 提供类似于 localStorage 的 API 同时支持 ES6 Promise API
- 支持存储多种类型的数据
- 支持所有现代的浏览器,在没有 IndexedDB 的浏览器使用 localStorage 存储
什么是 LocalForage
- Mozilla 开发的用于改善 web app 的离线体验的 JS 库
- 提供类似于 localStorage 的 API 同时支持 ES6 Promise API
- 支持存储多种类型的数据
- 支持所有现代的浏览器,在没有 IndexedDB 的浏览器使用 localStorage 存储
IndexedDB
IndexedDB 是一个为了能够在客户端存储可观数量的结构化数据,并且在这些数据上使用索引进行高性能检索的API;key-value 数据库。
兼容性
2016.10 caniuse.com 的数据,基本所有浏览器都支持
容量限制
Firefox: 无限制,超过50MB 需请求
Chrome: 磁盘剩余容量的1/15,最大4GB
驱动优先级
- IndexedDB
- WebSQL
- localStorage
安装
html
<script src="localforage.js"></script>
API
js
localforage.getItem('mykey').then((value) => {
value === null; // key 不存在或存的是 undefined
});
localforage.setItem('mykey', 'myvalue').then((value) => {
value === 'myvalue'; // myvalue 支持 string, number, array, object, binary
});
localforage.removeItem('mykey').then(() => {
console.log('移除成功');
});
localforage.clear().then(() => {
console.log('清空数据库');
});
localforage.length().then((len) => {
console.log('key 数量: ', len);
});
localforage.key(0).then((keyName) => {
console.log('第0个key: ', keyName);
});
localforage.keys().then((keys) => {
console.log('所有key: ', keys);
});
localforage.iterate((value, key, iterationNumber) => {
console.log([key, value]);
if (iterationNumber === 10) {
return [key, value]; // 提前退出
}
}).then((result) => {
console.log('Iteration has completed: ', result);
});