CacheStorage is a storage mechanism in browsers for storing and retrieving network requests and response. It stores a pair of Request and Response objects. The Request as the key and Response as the value.
The Request object is used to send an HTTP request over a network, the network responds with a Response object from the server. Now, the two forms a pair, much like a question and an answer.
Let’s say we request for an image from a server:
// question: Please, server I need an image `image.png`
const req = new Request('/image.jpg)
We will get the response like this:
// Server: Hello Request, see the image you requested. Much please doing buisness with you
const res = new Response(new Blob([data]),{type:'image/jpeg'})
// here, res contains the image data
req and res will be stored in the Cache like this:
Cache
-------------
key | value
-------------
req | res
So to get res Response object we will reference it from req which is it’s key.
log(Cache[req])
It will return req.
If we request for a particular page:
const req1 = new Request('/index.html')
The response will be like this:
const res1 = new Response(body);
Now, the Cache will be updated:
Cache
-------------
key | value
-------------
req | res
req1 | res1
CacheStorage and Service Workers
CacheStorage is not a Service Worker API, but it enables SW to cache network responses so that they can provide offline capabilities when the user is disconnected from the network. You can use other storage mechanisms in SW. For example, IndexedDB, a SQL database in the browser, can be used to store network responses.
CacheStorage can be used in the DOM thread not only in the Worker thread:
<script>
if('caches' in window) {
caches.open('cache_name').then((cache) => {
// ...
}).catch((err) => {
// ...
})
}
</script>
Though The CacheStorage was created to enable SW store network requests and responses as we said earlier it can also be used in the DOM(window, iframe) as a storage utility.
For example, we can store a user’s password, key or an application state and retrieve them whenever we want.
caches Object
The caches (an instance of CacheStorage) object is used to access the CacheStorage, to retrieve, store and delete objects.
The caches object is global, it is located in the window object.
To detect whether your browser supports CacheStorage, run the below code:
<script>
if ('caches' in window) {
caches.open('cache_name').then((cache) => {
// ...
}).catch((err) => {
// ...
})
}
</script>
The caches object stores and maintains a list of Caches created. In order to manage this Caches, the caches object has many methods to help it carry out its maintenance work. We will look at the methods below.
CacheStorage API Methods — Creating a Cache
We can create a Cache by calling the open(…) method. The open method takes a string which bears the name of the cache to open.
When the open method is called with the cache name, it searches for the cache name in its list of Caches and returns the Cache with reference to the cache name. If the Cache is not found, the open method creates the Cache and returns a handle to it.
<script>
const l = console.log
if ('caches' in window) {
caches.open('cache_name').then((cache) => {
l(cache)
}).catch((err) => {
l(err)
})
}
</script>
Note: CacheStorage API is Promise-based. They return PRomise, so you have to resolve and reject them to get their status.
In the above, we tried opening the cache_name Cache by calling the open method in the caches object with the cache name as the parameter. The method returns a Promise, it resolves if the Cache is successfully created or rejects if the operation failed.
We used the then method to get the resolved value. The resolved value is a handle to the Cache.
CacheStorage API Methods — Checking a Cache
We can check if a Cache object exists by calling the has() method with the name of the cache object.
<script>
const l = console.log
if ('caches' in window) {
caches.has('cache_name').then((bool) => {
l(bool)
}).catch((err) => { })
}
</script>
It returns a Promise and a boolean value bool, the bool is true if the Cache was found or false if the Cache wasn't found.
For example:
<script>
const l = console.log if ('caches' in window) { caches.open('cache_name').then((cache) => {
We added to the code in our previous section. We created the cache-name cache, then called has() method passing in the cache name cache-name. Being previously created this will log true. Next, we called the has method passing in cache_name_1, this will log false because we didn't create a cache_name_1 cache.
CacheStorage API Methods — Delete a Cache
We can delete an already existing Cache by using the delete method. We create a cache like this:
<script>
const l = console.log if ('caches' in window) {
caches.open('cache_name').then((cache) => {
alert(cache.add)
}).catch((err) => {
l(err)
})
}
</script>
We can delete the cache-name Cache by calling the delete() method and passing the name of the cache cache-name:
<script>
const l = console.log if ('caches' in window) { caches.open('cache_name').then((cache) => {
l(cache)
}).catch((err) => {
l(err)
}) caches.delete('cache_name').then((bool) => {
l(bool) // true
}).catch((err) => { }) }
</script>
It returns a Promise that resolves with a boolean. If the boolean is true that means the Cache was successfully deleted. If it succeeds we will have true logged in our console.
If we call the has method after the delete call, it will surely log false because it won’t find the Cache because it has been deleted by the delete call.
<script>
const l = console.log if ('caches' in window) {
caches.open('cache_name').then((cache) => {
l(cache.add)
}).catch((err) => {
l(err)
}) caches.delete('cache_name').then((bool) => {
l(bool)
}) caches.has('cache_name').then((bool) => {
l(bool) // surely logs false if `delete(...)` succeeds.
}).catch((err) => { })
}
</script>
CacheStorage API Methods — Listing the Cache objects
To view Cache objects that have been created we use the keys method to list all the Cache objects in our storage.
<script>
const l = console.log if ('caches' in window) {
caches.open('cache_name').then((cache) => {
l(cache)
}).catch((err) => {
l(err)
})
caches.open('cache_name-1').then((cache) => {
l(cache)
}).catch((err) => {
l(err)
})
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (