javascript - 如何在 Progressive Web Apps 中的浏览器内存储离线存储永久数据?
问题描述
是否可以将永久数据存储在浏览器内的离线存储中?如果有任何解决方案,请帮助我,以便我可以解决我的问题。我读了一些教程,但这对我没有用。提前致谢!
解决方案
让我们直接提出关于离线存储数据的一般建议:
- 对于离线加载应用所需的网络资源,请使用缓存 API(服务工作者的一部分)。
- 对于所有其他数据,请使用 IndexedDB(带有 Promise 包装器)。
在我告诉你每个浏览器的存储限制后,我会告诉你如何使用这两者。
- Chrome 支持使用 <6% 的可用空间
- Firefox 支持使用 <10% 的可用空间
- Safari 支持使用 <50MB
- Internet Explorer 10 支持使用 <250MB
- 使用 Edge,它取决于卷大小
使用缓存 api 的服务工作者的工作示例是
var CACHE_VERSION = 1;
// Shorthand identifier mapped to specific versioned cache.
var CURRENT_CACHES = {
font: 'font-cache-v' + CACHE_VERSION
};
self.addEventListener('activate', function(event) {
var expectedCacheNames = Object.values(CURRENT_CACHES);
// Active worker won't be treated as activated until promise
// resolves successfully.
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (!expectedCacheNames.includes(cacheName)) {
console.log('Deleting out of date cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', function(event) {
console.log('Handling fetch event for', event.request.url);
event.respondWith(
// Opens Cache objects that start with 'font'.
caches.open(CURRENT_CACHES['font']).then(function(cache) {
return cache.match(event.request).then(function(response) {
if (response) {
console.log('Found response in cache:', response);
return response;
}
console.log('Fetching request from the network');
return fetch(event.request).then(function(networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
});
}).catch(function(error) {
// Handles exceptions that arise from match() or fetch().
console.error('Error in fetch handler:', error);
throw error;
});
})
);
});
而且我不确定如何使用 IndexedDB 其他一些方法是
推荐阅读
- javascript - UDEV Shell 脚本权限问题
- flutter - 产生新状态不更新 UI
- vim - vim 语法高亮注释,可以是一行或块
- python - Opencv HoughCircles 在二值图像上表现不佳?
- javascript - useEffect 依赖数组中不必要的参数
- javascript - Javascript 输出一个最接近于零的数字,其中包含一个使用了 .map 函数的数组
- r - R RegEx gsub() 等效于 CSV 文件中的“行操作>删除空行(包含空白字符)”
- python - Google Cloud Storage 中的“StartAfter”参数等价于列出对象
- dbt - 什么是 .user.yml 文件?它的目的是什么?
- docker - 我可以在 VS Code 中使用相同的 DockerFile 进行远程开发和生产构建吗?