/

The Cache API Guide: A Powerful Resource Caching Tool

The Cache API Guide: A Powerful Resource Caching Tool

The Cache API, which is part of the Service Worker specification, provides developers with more control over resource caching. It allows you to cache URL-addressable resources such as assets, web pages, and HTTP APIs responses, enhancing the performance of your web applications. However, it’s important to note that the Cache API is not designed to cache individual data chunks, which falls under the responsibility of the IndexedDB API.

Currently, the Cache API is supported in Chrome (version 40 and above), Firefox (version 39 and above), and Opera (version 27 and above). Recently, Safari and Edge have introduced support for the Cache API, while Internet Explorer does not support it. On mobile devices, the Cache API is well-supported on Android, specifically in the Android Webview and Chrome for Android. On iOS, it’s only available for Opera Mobile and Firefox Mobile users.

In this guide, we’ll cover the following topics:

Introduction

The Cache API is a great asset for web developers looking to utilize resource caching effectively. By caching URL-addressable resources, you can enhance the performance and user experience of your web applications.

Detect if the Cache API is available

To determine if the Cache API is implemented in the browser, you can check for the existence of the caches object using the following code:

1
2
3
if ('caches' in window) {
// The Cache API is available
}

Initialize a cache

To start using the Cache API, you need to open a cache object using the caches.open API. This method returns a promise that resolves to a cache object ready to be used. Here’s an example:

1
2
3
caches.open('mycache').then(cache => {
// Start using the cache
});

In this example, ‘mycache’ is an identifier that you can customize to give a unique name to your cache. If the cache doesn’t exist yet, caches.open creates it for you.

Add items to the cache

The cache object provides two methods for adding items to the cache: cache.add() and cache.addAll().

cache.add()

The cache.add() method accepts a single URL as its argument and fetches the resource to cache it. Here’s an example:

1
2
3
caches.open('mycache').then(cache => {
cache.add('/api/todos');
});

To have more control over the fetch process, you can pass a Request object as the argument instead of a URL. A Request object is part of the Fetch API specification. Here’s an example:

1
2
3
4
5
6
caches.open('mycache').then(cache => {
const options = {
// Add your options here
};
cache.add(new Request('/api/todos', options));
});

cache.addAll()

The cache.addAll() method accepts an array of URLs and caches all the resources in that array. Once all the resources have been cached, it returns a promise. Here’s an example:

1
2
3
4
5
caches.open('mycache').then(cache => {
cache.addAll(['/api/todos', '/api/todos/today']).then(() => {
// All requests were cached
});
});

Manually fetch and add

If you need more granular control over the fetch process, you can use cache.put() instead of cache.add(). With this approach, you’re responsible for fetching the resource and then instructing the Cache API to store the response. Here’s an example:

1
2
3
4
5
6
const url = '/api/todos';
fetch(url).then(res => {
return caches.open('mycache').then(cache => {
return cache.put(url, res);
});
});

Retrieve an item from the cache

To retrieve an item from the cache, you can use the cache.match() method. It returns a Response object that contains the information about the request and the response of the network request. Here’s an example:

1
2
3
4
5
caches.open('mycache').then(cache => {
cache.match('/api/todos').then(res => {
// The 'res' variable holds the Response object
});
});

Get all the items in a cache

To retrieve all the items in a cache, you can use the cache.keys() method. It returns a promise that resolves to an array of Request objects, each containing the URL of a cached resource. Here’s an example:

1
2
3
4
5
caches.open('mycache').then(cache => {
cache.keys().then(cachedItems => {
// 'cachedItems' is an array of Request objects
});
});

Get all the available caches

To get a list of all the available caches, you can use the caches.keys() method. It returns a promise that resolves to an array containing the keys of every cache available. Here’s an example:

1
2
3
caches.keys().then(keys => {
// 'keys' is an array with the list of cache keys
});

Remove an item from the cache

You can use the delete() method of a cache object to remove a specific cached resource. Here’s an example:

1
2
3
caches.open('mycache').then(cache => {
cache.delete('/api/todos');
});

Delete a cache

To delete a cache and its cached items from the system, you can use the caches.delete() method. It accepts the cache identifier as an argument and returns a promise. Here’s an example:

1
2
3
caches.delete('mycache').then(() => {
// The cache was deleted successfully
});

By following this guide, you can leverage the power of the Cache API to improve the caching capabilities of your web applications, resulting in faster and more efficient user experiences.

tags: Cache API, Service Worker, Resource Caching, IndexedDB API, Web Performance