缓存动态视图 PWA ASP



我有一个关于PWA缓存的问题。
我想让用户选择要缓存的列表。例如: 用户创建几个列表,然后选择一个列表,以保存以供离线使用。 当他离线时,他只能打开 2 个视图:

  1. 像"您处于离线状态,是否要打开已保存的列表?"(如果存在(
  2. 使用保存的列表查看。

目前,我正在缓存用户访问的所有视图,但无法缓存包含动态数据的视图。
我正在使用PWA.essentials来做PWA。

services.AddProgressiveWebApp(new PwaOptions
{
RegisterServiceWorker = true,
RegisterWebmanifest = false,
Strategy = ServiceWorkerStrategy.NetworkFirst,
RoutesToPreCache = "/, /Home/Offline, /Home/Saved_list",
OfflineRoute="Offline.html"
}); 

我已经创建了manifest.json。当我在 chrome 中使用开发模式时,我可以看到此时我正在缓存所有视图,这些视图包含具有更复杂路径的视图(如/控制器/视图/某物(。


我正在保存列表,该用户在"Offline.json"文件中选择,该文件也被缓存,但是当用户更改要保存的列表时,文件"offline.json"仍然没有更新。我的意思是我的 PWA 不会用新的替换它。所以我有一个关于如何将动态列表保存到浏览器缓存,然后设置离线路由的问题。

由 pwa.essentials 创建的 Service Worker :

(function () {
'use strict';
// Update 'version' if you need to refresh the cache
var version = 'v1.0::NetworkFirst';
var offlineUrl = "Offline.html";
// Store core files in a cache (including a page to display when offline)
function updateStaticCache() {
return caches.open(version)
.then(function (cache) {
return cache.addAll([
offlineUrl,
'/','/Home','/Generate/Select_mode'
]);
});
}
function addToCache(request, response) {
if (!response.ok)
return;
var copy = response.clone();
caches.open(version)
.then(function (cache) {
cache.put(request, copy);
});
}
self.addEventListener('install', function (event) {
event.waitUntil(updateStaticCache());
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys()
.then(function (keys) {
// Remove caches whose name is no longer valid
return Promise.all(keys
.filter(function (key) {
return key.indexOf(version) !== 0;
})
.map(function (key) {
return caches.delete(key);
})
);
})
);
});
self.addEventListener('fetch', function (event) {
var request = event.request;
// Always fetch non-GET requests from the network
if (request.method !== 'GET') {
event.respondWith(
fetch(request)
.catch(function () {
return caches.match(offlineUrl);
})
);
return;
}
event.respondWith(
fetch(request)
.then(function (response) {
// Stash a copy of this page in the cache
addToCache(request, response);
return response;
})
.catch(function () {
return caches.match(request)
.then(function (response) {
return response || caches.match(offlineUrl);
})
.catch(function () {
if (request.headers.get('Accept').indexOf('image') !== -1) {
return new Response('<svg role="img" aria-labelledby="offline-title" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg"><title id="offline-title">Offline</title><g fill="none" fill-rule="evenodd"><path fill="#D8D8D8" d="M0 0h400v300H0z"/><text fill="#9B9B9B" font-family="Helvetica Neue,Arial,Helvetica,sans-serif" font-size="72" font-weight="bold"><tspan x="93" y="172">offline</tspan></text></g></svg>', { headers: { 'Content-Type': 'image/svg+xml' } });
}
});
})
);
});
})();

您将用户选择的页面列表保存在服务器端的offline.json中,并且您也在缓存该文件。根据PWA的工作,缓存资源从缓存而不是从服务器提供,直到缓存被删除/清除。

您可以采取2种方法。

  1. 每当用户添加到 offline.json 时,您都需要强制服务工作进程更新脱机文件。

  2. 您可以简单地将用户选择存储在本地存储中,然后从那里将页面添加到缓存列表中。

最新更新