我一直在阅读html5rocks服务工作者文章简介,并创建了一个基本的服务工作者来缓存页面,JS和CSS按预期工作:
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
'/'
];
// Set the callback for the install step
self.addEventListener('install', function (event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
// IMPORTANT: Clone the request. A request is a stream and
// can only be consumed once. Since we are consuming this
// once by cache and once by the browser for fetch, we need
// to clone the response
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function(response) {
// Check if we received a valid response
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have 2 stream.
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
Run Code Online (Sandbox Code Playgroud)
当我对CSS进行更改时,由于服务工作者正在从缓存中正确返回CSS,因此未进行此更改.
如果我要更改HTML,JS或CSS,我将如何确定服务工作者是否可以从服务器加载新版本而不是缓存?我尝试在CSS导入上使用版本标记,但这似乎不起作用.
Jef*_*ick 41
一种选择就是使用服务工作者的缓存作为后备,并始终尝试通过网络优先进入网络fetch().但是,您会失去缓存优先策略所带来的性能提升.
另一种方法是使用sw-precache生成服务工作者脚本作为站点构建过程的一部分.
它生成的服务工作者将使用文件内容的散列来检测更改,并在部署新版本时自动更新缓存.它还将使用缓存清除URL查询参数来确保您不会意外地使用HTTP缓存中的过时版本填充服务工作缓存.
在实践中,您将最终得到一个使用性能友好的缓存优先策略的服务工作者,但缓存将在页面加载后"在后台"更新,以便下次访问时,一切都很新鲜.如果需要,可以向用户显示一条消息,让他们知道有可用的更新内容并提示他们重新加载.
这里的主要问题是,当您的新 Service Worker 安装时,他会获取由前一个 Service Worker 处理的请求,并且他很可能从缓存中获取资源,因为这是您的缓存策略。然后,即使您使用新代码、新缓存名称、调用 来更新服务工作人员self.skipWaiting(),他仍然会将旧资源放入缓存中!
要知道的一件事是,每次代码脚本更改时,服务工作线程都会触发安装事件,因此您不需要使用版本标记或其他任何东西,只需保留相同的文件名就可以了,甚至建议这样做。浏览器还有其他方式认为您的 Service Worker 已更新。
1. 重写您的安装事件处理程序:
我不使用,cache.addAll因为它坏了。事实上,如果无法获取要缓存的一项且仅有一项资源,则整个安装将失败,甚至不会将一个文件添加到缓存中。现在假设您的要缓存的文件列表是从存储桶自动生成的(这是我的情况),并且您的存储桶已更新并且一个文件被删除,那么您的 PWA 将安装失败,但事实并非如此。
sw.js
self.addEventListener('install', (event) => {
// prevents the waiting, meaning the service worker activates
// as soon as it's finished installing
// NOTE: don't use this if you don't want your sw to control pages
// that were loaded with an older version
self.skipWaiting();
event.waitUntil((async () => {
try {
// self.cacheName and self.contentToCache are imported via a script
const cache = await caches.open(self.cacheName);
const total = self.contentToCache.length;
let installed = 0;
await Promise.all(self.contentToCache.map(async (url) => {
let controller;
try {
controller = new AbortController();
const { signal } = controller;
// the cache option set to reload will force the browser to
// request any of these resources via the network,
// which avoids caching older files again
const req = new Request(url, { cache: 'reload' });
const res = await fetch(req, { signal });
if (res && res.status === 200) {
await cache.put(req, res.clone());
installed += 1;
} else {
console.info(`unable to fetch ${url} (${res.status})`);
}
} catch (e) {
console.info(`unable to fetch ${url}, ${e.message}`);
// abort request in any case
controller.abort();
}
}));
if (installed === total) {
console.info(`application successfully installed (${installed}/${total} files added in cache)`);
} else {
console.info(`application partially installed (${installed}/${total} files added in cache)`);
}
} catch (e) {
console.error(`unable to install application, ${e.message}`);
}
})());
});
Run Code Online (Sandbox Code Playgroud)
2. 当(新)Service Worker 激活时清理旧缓存:
sw.js
// remove old cache if any
self.addEventListener('activate', (event) => {
event.waitUntil((async () => {
const cacheNames = await caches.keys();
await Promise.all(cacheNames.map(async (cacheName) => {
if (self.cacheName !== cacheName) {
await caches.delete(cacheName);
}
}));
})());
});
Run Code Online (Sandbox Code Playgroud)
3. 每次更新资源时我都会更新缓存名称:
sw.js
// this imported script has the newly generated cache name (self.cacheName)
// and a list of all the files on my bucket I want to be cached (self.contentToCache),
// and is automatically generated in Gitlab based on the tag version
self.importScripts('cache.js');
// the install event will be triggered if there's any update,
// a new cache will be created (see 1.) and the old one deleted (see 2.)
Run Code Online (Sandbox Code Playgroud)
4.缓存中的句柄Expires和Cache-Control响应头
我在服务工作人员的获取事件处理程序中使用这些标头来捕获当资源过期/应该刷新时是否应该通过网络请求资源。
基本示例:
// ...
try {
const cachedResponse = await caches.match(event.request);
if (exists(cachedResponse)) {
const expiredDate = new Date(cachedResponse.headers.get('Expires'));
if (expiredDate.toString() !== 'Invalid Date' && new Date() <= expiredDate) {
return cachedResponse.clone();
}
}
// expired or not in cache, request via network...
} catch (e) {
// do something...
}
// ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25277 次 |
| 最近记录: |