javascript - 如果页面脱机,如何从服务人员获得对索引 js 的响应
问题描述
我正在使用城市列表服务,在我的主页中使用 HTTP 请求我已经获取列表并显示在自动完成中,所以我想知道通过使用服务工作者如何将该城市列表存储在缓存中并在离线模式下使用
解决方案
看看这里:
首先,您已经安装了一个服务人员。接下来,您已经知道需要拦截什么样的请求以及您希望如何响应请求。(缓存策略)。
在你的 index.html 添加
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
})
.catch(function(error) {
console.log('Service worker registration failed, error:', error);
});
}
然后在你的 service-worker.js 添加
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open('cache-name').then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
这将缓存您的所有网络 GET 请求。因此,从您的下一个请求开始,它将首先检查缓存,并且仅当数据不存在时才会进行网络获取。
推荐阅读
- c++ - gdb "skip" 命令不能跳过 libc++ 头文件
- html - Bootstrap 导航栏下拉菜单在 Catalina 上不起作用?
- java - 如何在 NotificationListnerService 的帮助下在通知中按下标记为已读按钮?
- c++ - 从一对迭代器构造 std::vector。允许调用哪些元素构造函数?
- php - 我可以让 Azure 应用使用 mail() 函数发送电子邮件吗?
- algorithm - 最坏情况分析
- javascript - 有没有办法在 react-native 的单独文件中定义自定义对象的道具?
- amazon-web-services - Amazon Cognito Oauth2 Native App:最佳实践
- excel - VBA:有没有办法获取/读取模块属性?
- python - Beautifulsoup 在 xml 文档中添加/插入 html 标记行