api 缓存_缓存API

雨点打透心脏的1/2处 2023-02-22 03:36 28阅读 0赞

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 …

  1. if('caches' in window) {
  2. // Has support!
  3. }

…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调用:

  1. caches.open('test-cache').then(function(cache) {
  2. // Cache is created and accessible
  3. });

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对象充当浏览器存储的响应的键。 通过两种主要方法对缓存进行简单添加: addaddAll 。 您可以为这些方法提供应获取和缓存的URL字符串或Request对象。 您可以通过阅读我的提取API帖子来了解有关Request对象的更多信息。

To batch add URLs to cache, you can use the addAll method:

要批量添加要缓存的URL,可以使用addAll方法:

  1. caches.open('test-cache').then(function(cache) {
  2. cache.addAll(['/', '/images/logo.png'])
  3. .then(function() {
  4. // Cached!
  5. });
  6. });

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方法:

  1. caches.open('test-cache').then(function(cache) {
  2. cache.add('/page/1'); // "/page/1" URL will be fetched and cached!
  3. });

add can also accept a custom Request:

add也可以接受自定义Request

  1. caches.open('test-cache').then(function(cache) {
  2. cache.add(new Request('/page/1', { /* request options */ }));
  3. });

Similar to add is put whereby you can add a URL and its Response object:

类似的addput ,让你可以添加URL和Response的对象:

  1. fetch('/page/1').then(function(response) {
  2. return caches.open('test-cache').then(function(cache) {
  3. return cache.put('/page/1', response);
  4. });
  5. });

探索缓存 (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对象的数组:

  1. caches.open('test-cache').then(function(cache) {
  2. cache.keys().then(function(cachedRequests) {
  3. console.log(cachedRequests); // [Request, Request]
  4. });
  5. });
  6. /*
  7. Request {
  8. bodyUsed: false
  9. credentials: "omit"
  10. headers: Headers
  11. integrity: ""
  12. method: "GET"
  13. mode: "no-cors"
  14. redirect: "follow"
  15. referrer: ""
  16. url: "https://fullhost.tld/images/logo.png"
  17. }
  18. */

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.matchcache.matchAll

  1. caches.open('test-cache').then(function(cache) {
  2. cache.match('/page/1').then(function(matchedResponse) {
  3. console.log(matchedResponse);
  4. });
  5. });
  6. /*
  7. Response {
  8. body: (...),
  9. bodyUsed: false,
  10. headers: Headers,
  11. ok: true,
  12. status: 200,
  13. statusText: "OK",
  14. type: "basic",
  15. url: "https://davidwalsh.name/page/1"
  16. }
  17. */

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方法:

  1. caches.open('test-cache').then(function(cache) {
  2. cache.delete('/page/1');
  3. });

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

  1. caches.keys().then(function(cacheKeys) {
  2. console.log(cacheKeys); // ex: ["test-cache"]
  3. });

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:

拥有缓存键名后,删除缓存很简单:

  1. caches.delete('test-cache').then(function() {
  2. console.log('Cache successfully deleted!');
  3. });

You’ll often delete a cache when you’re replacing with a new one (to trigger re-installation of a new service worker):

当您要替换新的缓存时,通常会删除缓存(以触发新服务工作者的重新安装):

  1. // Assuming `CACHE_NAME` is the newest name
  2. // Time to clean up the old!
  3. var CACHE_NAME = 'version-8';
  4. // ...
  5. caches.keys().then(function(cacheNames) {
  6. return Promise.all(
  7. cacheNames.map(function(cacheName) {
  8. if(cacheName != CACHE_NAME) {
  9. return caches.delete(cacheName);
  10. }
  11. })
  12. );
  13. });

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 缓存

发表评论

表情:
评论列表 (有 0 条评论,28人围观)

还没有评论,来说两句吧...

相关阅读

    相关 前端 api 请求缓存方案

    在开发 web 应用程序时,性能都是必不可少的话题。对于webpack打包的单页面应用程序而言,我们可以采用很多方式来对性能进行优化,比方说 tree-shaking、模块懒加