gpt4 book ai didi

javascript - 如何让 Service Worker 从 API 缓存数据并在需要时更新缓存

转载 作者:行者123 更新时间:2023-12-04 09:30:52 24 4
gpt4 key购买 nike

我将我的 React 应用程序转换为 PWA,它部分工作正常。
我遵循了本教程:https://medium.com/@toricpope/transform-a-react-app-into-a-progressive-web-app-pwa-dea336bd96e6
但是这篇文章只展示了如何缓存静态数据,我还需要存储来自服务器的数据,我可以按照这篇文章的第一个答案的说明来做:How can I cache data from API to Cache Storage in React PWA?并将存储数据的firebase地址插入数组urlsToCache ,由应存储到缓存中的文件填充。
到目前为止一切顺利,但是在将数据存储到缓存中之后,应用程序停止从服务器获取数据并仅使用缓存中的数据加载页面,即使服务器已更新。这是我需要解决的问题。
简而言之,我需要从服务器获取数据,将其存储到缓存中,以便在应用程序离线时使用它,并在每次到达服务器时更新缓存。
我正在尝试遵循本指南,但没有成功:https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#serving-suggestions
这是我的 worker.js 文件:

var CACHE_NAME = 'pwa-task-manager';
var urlsToCache = [
'/',
'/completed',
'/index.html',
'/static/js/main.chunk.js',
'/static/js/0.chunk.js',
'/static/js/1.chunk.js',
'/static/js/bundle.js',
'/calculadora',
'https://calc-marmo.firebaseio.com/clientes.json',
'https://calc-marmo.firebaseio.com/adm.json',
];

// Install a service worker
self.addEventListener('install', event => {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});

// Cache and return requests
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});

// Update a service worker
self.addEventListener('activate', event => {
var cacheWhitelist = ['pwa-task-manager'];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
任何帮助将非常感激。

最佳答案

这听起来像是你需要一个网络优先策略,这在食谱中没有提到。此策略类似于网络回退到缓存,但始终将响应存储在缓存中。
解释:https://developers.google.com/web/tools/workbox/modules/workbox-strategies#network_first_network_falling_back_to_cache
代码示例(如果您不使用工作箱):https://gist.github.com/JMPerez/8ca8d5ffcc0cc45a8b4e1c279efd8a94

关于javascript - 如何让 Service Worker 从 API 缓存数据并在需要时更新缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com