JavaScript中的缓存API

了解如何使用JavaScript中的Cache API缓存资源。

JavaScript中的缓存API

Cache API允许服务工作者对要缓存的资源(HTML页面、CSS、JavaScript文件、图片、JSON等)进行控制。通过Cache API,服务工作者可以缓存资源以供脱机使用,并在以后检索它们。

检测Cache支持

检查 caches 对象在 window 中是否可用。

let isCacheSupported = 'caches' in window; 

caches 是 CacheStorage 的一个实例。

创建/初始化Cache

我们可以使用 open 方法创建一个具有 name 的缓存,这将返回 promise。如果缓存已经存在,则不会创建新的缓存。

caches.open('cacheName').then( cache => { 
}); 
  • 你不能访问为其他源(域)设置的缓存。
  • 你正在创建的缓存将为你的域创建。
  • 你可以为同一个域添加多个缓存,可以通过 caches.keys() 访问。

将项目添加到缓存

可以使用三种方法 add,addAll,set 来缓存资源。add() 和 addAll() 方法自动获取资源并对其进行缓存,而在 set 方法中,我们将获取数据并设置缓存。

add

let cacheName = 'userSettings'; 
let url = '/api/get/usersettings'; 
caches.open(cacheName).then( cache => { 
   cache.add(url).then( () => { 
       console.log("Data cached ") 
    }); 
}); 

在上面的代码中,内部对 /api/get/usersettings url的请求已发送到服务器,一旦接收到数据,响应将被缓存。

addAll

addAll 接受URL数组,并在缓存所有资源时返回Promise。

let urls = ['/get/userSettings?userId=1', '/get/userDetails']; 
caches.open(cacheName).then( cache => { 
cache.addAll(urls).then( () => { 
       console.log("Data cached ") 
    }); 
}); 

Cache.add/Cache.addAll 不缓存 Response.status 值不在200范围内的响应,Cache.put 可以让你存储任何请求/响应对。

put

put 为当前的 Cache 对象添加一个key/value对,在 put 中,我们需要手动获取请求并设置值。

注意:put() 将覆盖先前存储在高速缓存中与请求匹配的任何键/值对。

let cacheName = 'userSettings'; 
let url = '/api/get/userSettings'; 
fetch(url).then(res => { 
  return caches.open(cacheName).then(cache => { 
    return cache.put(url, res); 
  }) 
}) 

从缓存中检索

使用 cache.match() 可以得到存储到URL的 Response。

const cacheName = 'userSettings' 
const url = '/api/get/userSettings' 
caches.open(cacheName).then(cache => { 
  cache.match(url).then(settings => { 
    console.log(settings); 
  } 
}); 

settings 是一个响应对象,它看起来像

Response { 
  body: (...), 
  bodyUsed: false, 
  headers: Headers, 
  ok: true, 
  status: 200, 
  statusText: "OK", 
  type: "basic", 
  url: "https://test.com/api/get/userSettings" 
} 

检索缓存中的所有项目

cache 对象包含 keys 方法,这些方法将拥有当前缓存对象的所有url。

caches.open(cacheName).then( (cache) => { 
  cache.keys().then((arrayOfRequest) => { 
      console.log(arrayOfRequest); // [Request,  Request] 
  }); 
}); 

arrayOfRequest是一个Request对象数组,其中包含有关请求的所有详细信息。

检索所有缓存

caches.keys().then(keys => { 
  // keys是一个数组,其中包含键的列表 
}) 

从缓存中删除项目

可以对 cache 对象使用 delete 方法来删除特定的缓存请求。

相关推荐