cache API简介

cache API是一个很强大的API,它可以在window环境和serviceWorker环境使用,配合serviceWorker可以让我们自己来管理缓存。

caches

caches是一个全局接口,可以在window和worker下访问到。我们可以使用caches.open来获取(如果没有的话会创建)一个cache对象:

caches.open('test').then(cache => console.log(cache));

此外, caches还有以下API:

caches.has('test') // 有没有cacheName为test的cache
caches.delete('test') // 删除一个cache对象
caches.match('https;//www.baidu.com') //找到一个url对应的cache 响应
caches.match('https;//www.baidu.com', {cacheName:'test'}) //在指定的cacheName下找到一个url对应的cache 响应

需要注意的是,上面的API都返回一个promise

cache对象

如果把caches理解成数据库,那么cache对象就像一张表,关联了request 和 response, cache对象有以下方法:

cache.add, cache.addAll

这两个方法都可以把一些请求缓存下来,区别在于addAll可以接受多个请求或者url。常用于提前缓存一些静态资源。

cache.add('https://www.baidu.com?a=1');

// serviceWorker
addEventListener('install', event => {
  const preCache = async () => {
    const cache = await caches.open('static-v1');
    return cache.addAll([
      '/',
      '/about/',
      '/static/styles.css'
    ]);
  };
  event.waitUntil(preCache());
});

cache.put

cache.put 接受两个参数,一个request, 一个response,这让我们可以更新缓存或者伪造响应。

caches.open('test').then((cache) => {
    cache.put('/hello', new Response('hello word', {status: 200}))
} )

cache.match

与caches.match用法一样,匹配一个request对应的response,如果没有,则返回undefined

caches.open('test').then((cache) => {

    cache.match('/hello').then(res => res?.text()).then(console.log)
} )

cache.delete

删除一个缓存,成功返回true,失败返回false

caches.open('test').then((cache) => {

    cache.delete('/hello').then(console.log)
} )

总结

上面就是cache API的内容了,当它可以service Worker一起使用的时候,可以发挥出巨大的威力

posted @ 2023-02-02 19:18  饭特稠  阅读(506)  评论(0编辑  收藏  举报