api 缓存_缓存API
api 缓存
The awesome ServiceWorker API is meant to give developers a bit more control over what is and isn’t cached, and how. Sure we can play games with ETags and the like but doing it programmatically with JavaScript just feels better, more controllable. As with every API, however, adding stuff to cache isn’t just fun and games — you have to do the cleanup work yourself too, and by “cleanup work” I mean having to delete cache.
出色的ServiceWorker API旨在使开发人员对缓存的内容和不缓存的内容以及如何进行更多控制。 当然,我们可以使用ETags等玩游戏,但是使用JavaScript以编程方式进行操作会感觉更好,更可控。 但是,与每个API一样,向缓存中添加内容不仅很有趣,而且也很有趣-您也必须自己进行清理工作,而通过“清理工作”,我的意思是必须删除缓存。
Let’s have a look at how you can get caches, add and delete requests from caches, and how you can then delete an entire cache!
让我们看一下如何获取缓存,从缓存中添加和删除请求以及如何删除整个缓存!
检测cache
API (Detecting the cache
API)
To detect if the browser supports the Cache API…
要检测浏览器是否支持Cache API …
if('caches' in window) {
// Has support!
}
…check for the presence of the caches
object within the window
.
…检查window
是否存在caches
对象。
创建一个缓存 (Creating a Cache)
Creating a cache requires a caches.open
call with a cache name:
创建缓存需要使用缓存名称进行caches.open
调用:
caches.open('test-cache').then(function(cache) {
// Cache is created and accessible
});
The caches.open
call returns a Promise and the cache
object that was either created or existed before the open
call.
caches.open
调用返回一个Promise和在open
调用之前创建或存在的cache
对象。
添加到缓存 (Adding to Cache)
You can think of a cache as an array of Request
objects which act as keys to their responses which are stored by the browser. Simple addition to cache is happens via two main methods: add
and addAll
. You can provide these methods a string for the URL that should be fetched and cached or a Request
object. You can learn more about Request
objects by reading my fetch API post.
您可以将缓存视为Request
对象的数组,这些Request
对象充当浏览器存储的响应的键。 通过两种主要方法对缓存进行简单添加: add
和addAll
。 您可以为这些方法提供应获取和缓存的URL字符串或Request
对象。 您可以通过阅读我的提取API帖子来了解有关Request
对象的更多信息。
To batch add URLs to cache, you can use the addAll
method:
要批量添加要缓存的URL,可以使用addAll
方法:
caches.open('test-cache').then(function(cache) {
cache.addAll(['/', '/images/logo.png'])
.then(function() {
// Cached!
});
});
The addAll
method accepts an array of URLs whose URLs and responses should be cached. addAll
returns a Promise. To add a single URL, use the add
method:
addAll
方法接受URL和响应应被缓存的URL数组。 addAll
返回一个Promise。 要添加一个URL,请使用add
方法:
caches.open('test-cache').then(function(cache) {
cache.add('/page/1'); // "/page/1" URL will be fetched and cached!
});
add
can also accept a custom Request
:
add
也可以接受自定义Request
:
caches.open('test-cache').then(function(cache) {
cache.add(new Request('/page/1', { /* request options */ }));
});
Similar to add
is put
whereby you can add a URL and its Response
object:
类似的add
被put
,让你可以添加URL和Response
的对象:
fetch('/page/1').then(function(response) {
return caches.open('test-cache').then(function(cache) {
return cache.put('/page/1', response);
});
});
探索缓存 (Exploring Cache)
To view requests that have already been cached, you can use the individual cache’s keys
method to retrieve an array of cached Request
objects:
要查看已经缓存的请求,可以使用单个缓存的keys
方法来检索缓存的Request
对象的数组:
caches.open('test-cache').then(function(cache) {
cache.keys().then(function(cachedRequests) {
console.log(cachedRequests); // [Request, Request]
});
});
/*
Request {
bodyUsed: false
credentials: "omit"
headers: Headers
integrity: ""
method: "GET"
mode: "no-cors"
redirect: "follow"
referrer: ""
url: "https://fullhost.tld/images/logo.png"
}
*/
If you’d like to view the response of a cached Request
, you can do so by using cache.match
or cache.matchAll
:
如果您想查看缓存的Request
的响应,可以使用cache.match
或cache.matchAll
:
caches.open('test-cache').then(function(cache) {
cache.match('/page/1').then(function(matchedResponse) {
console.log(matchedResponse);
});
});
/*
Response {
body: (...),
bodyUsed: false,
headers: Headers,
ok: true,
status: 200,
statusText: "OK",
type: "basic",
url: "https://davidwalsh.name/page/1"
}
*/
You can learn more about Response
objects by reading my fetch API post.
您可以阅读我的提取API帖子,以了解有关Response
对象的更多信息。
删除缓存的请求 (Removing a Cached Request)
To remove a request from cache, use the cache’s delete
method:
要从缓存中删除请求,请使用缓存的delete
方法:
caches.open('test-cache').then(function(cache) {
cache.delete('/page/1');
});
The cache will no longer contain /page/1
!
缓存将不再包含/page/1
!
获取现有的缓存名称 (Getting Existing Cache Names)
To get the names of existing caches, use caches.keys
:
要获取现有缓存的名称,请使用caches.keys
:
caches.keys().then(function(cacheKeys) {
console.log(cacheKeys); // ex: ["test-cache"]
});
window.caches.keys()
again returns a promise.
window.caches.keys()
再次返回promise 。
删除缓存 (Deleting A Cache)
Deleting a cache is simple once you have cache key name:
拥有缓存键名后,删除缓存很简单:
caches.delete('test-cache').then(function() {
console.log('Cache successfully deleted!');
});
You’ll often delete a cache when you’re replacing with a new one (to trigger re-installation of a new service worker):
当您要替换新的缓存时,通常会删除缓存(以触发新服务工作者的重新安装):
// Assuming `CACHE_NAME` is the newest name
// Time to clean up the old!
var CACHE_NAME = 'version-8';
// ...
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if(cacheName != CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
});
You’ll want to keep these snippets in your toolbox for when you look to become a service worker expert. Chrome and Firefox now have service worker support so you’ll be seeing many more sites/apps available (reliably) offline and loading at much faster rates. Enjoy!
当您希望成为服务工作者专家时,需要将这些代码片段保留在工具箱中。 Chrome和Firefox现在具有服务人员支持,因此您将看到(可靠地)有更多可用的站点/应用程序离线且加载速度更快。 请享用!
翻译自: https://davidwalsh.name/cache
api 缓存
还没有评论,来说两句吧...