gpt4 book ai didi

javascript - 渐进式 Web 应用程序上的缓存版本控制

转载 作者:行者123 更新时间:2023-11-28 05:24:48 25 4
gpt4 key购买 nike

当前 Service Worker 缓存的最佳实践是什么?

在对多个项目使用 Service Worker 和缓存后,我们在管理项目的缓存 Assets 时遇到了一些维护难题。

在大多数情况下,我们使用静态缓存(很可能是我们头痛的原因),并且我们的 sw.js 代码非常标准,如下所示:

var cacheName = 'v1:static';

// cache static assets during install phase
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cacheName).then(function (cache) {
return cache.addAll([
'./',
'./css/style.css',
'./css/vendor.css',
'./js/build/script.min.js',
'./js/build/vendor.min.js'
]).then(function () {
self.skipWaiting();
});
})
);
});

self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function (response) {
if (response) {
// retrieve from cache
return response;
}
// fetch as normal
return fetch(event.request);
})
);
});

一旦我们发布了应用程序的新版本,问题就开始出现,我们需要使用户的缓存失效。

建议使用哪些方法来更新缓存?我知道sw-precache或者手动更新cacheName变量(或者可能通过任务运行程序)的开发人员。还有其他选择吗?有没有办法只使一个文件而不是整个缓存失效?

谢谢

最佳答案

我建议您对您的项目进行 Assets 评估。确定静态 Assets 和动态 Assets 。一旦确定了纯静态的,就对其进行预缓存。

有两种方法可以做到这一点。 1)使用sw-toolbox或 2) 手动更新 Service Worker 文件的版本号,以便浏览器进行更新。

我知道您在使缓存和所有内容失效时所经历的痛苦。您可能想尝试/实现 sw-toolbox

sw-toolbox方法

const OFFLINE_URL = '/pages/offline/';

importScripts('sw-toolbox.js');

self.toolbox.precache([
<PATH_TO_STATIC_ASSET>
'manifest.json',
OFFLINE_URL,
'/'
]);

self.toolbox.router.default = self.toolbox.networkFirst;

self.toolbox.router.get('/(.*)', function (req, vals, opts) {
return self.toolbox.networkFirst(req, vals, opts)
.catch(function (error) {
if (req.method === 'GET' && req.headers.get('accept').includes('text/html')) {
return self.toolbox.cacheOnly(new Request(OFFLINE_URL), vals, opts);
}
throw error;
});
});

Google Service Worker 样板 - link

这也非常简单。唯一的缺点是,在每次部署时,您都必须更新 CACHE_VERSION 以便安装的服务工作线程自动更新。

另请注意,有 Workbox还。我还没有玩过那么多,所以我的方法可能已经过时了。他们说这是预缓存和工具箱的后代

关于javascript - 渐进式 Web 应用程序上的缓存版本控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40259323/

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