JavaScript Async - Cache
Written by Ian Elliot   
Monday, 06 May 2019
Article Index
JavaScript Async - Cache
An Example

So to save something in the cache and retrieve it you would use something like:

var response = await fetch(request);
var myCache = await caches.open("myCache");
await myCache.put(request, response); 
var response2 = await myCache.match(request);
var text = await response2.text();

Alternatively you could simply use add to both fetch and store the response:

var myCache = await caches.open("myCache");
await myCache.add(request); 
var response = await myCache.match(request);
var text = await response.text();

It is important to realize that you can store multiple responses to the same request. The search options also allow you to control the nature of the match. For example setting ignoreSearch to true ignores any query string in the URL.

It is also worth mentioning that at the moment there is some disagreement when the Promises will settle. Some browsers wait for the response to finish downloading, others don’t.

You can mange the cache using:

await myCache.delete(request);

which returns true if the request is found and deleted.

The keys method returns an array of keys that the request matches. If you don’t specify a request all of the keys are returned. A prime use of this is to delete all of the entries in a Cache object:

var keys=await myCache.keys();
for(req of keys){
	myCache.delete(req);
}

Notice that as we don’t await each of the deletes they occur in parallel.

If you want to delete an entire Cache object then use the CacheStorage object’s delete method:

caches.delete(cacheName);

If want to delete all of the Cache objects you can use the CacheStorage object’s keys method in a very similar way to deleting the entries in a Cache object.

var keys=await caches.keys();
for(cache of keys){
	caches.delete(cache);
}

You can also use the CacheStorage object’s match method to find a response irrespective of which Cache object it is stored in, and its has method to discover if a particular Cache object exists.

One interesting problem is finding out how much storage is available. You can do this using the storage API. This provides the estimator object which has two properties, quota and usage. So to find out how much you have used and how much is available:

var estimate = await navigator.storage.estimate();
console.log(estimate.usage);
console.log(estimate.quota);

Under Chrome the quota was: 65,941,658,828 bytes. The big problem is that this is an estimate and the documentation says that there might be more, but you can’t rely on it.

This is about all there is to say about the CacheStorage API, but there is the always problematic issue of security. CacheStorage will only work on HTTPS connections. Browsers that support CacheStorage generally provide an option to relax this constraint for testing purposes. It is also that case the HTTP from localhost is allowed.

coverasync

A Cache Example

Putting all of this together it is time for a very simple example. Let’s retrieve an image file, store it in a Cache object and then retrieve it from the Cache. The HTML is simply:

<body>
	<img id="image1"/>
	<img id="image2"/>
</body>

The code is just as simple, but as we want to use async and await it is all packaged into a function that can be called from the main program:

<script>
getImage();
async function getImage() {

Getting the image is simple, we need a request object and then we can retrieve it and display it:

var url = new URL("http://localhost/MainLogo.png");
var request = new Request(url, {						method: "GET"
					});
var response = await fetch(request);
var blob = await response.blob();
var objectURL = URL.createObjectURL(blob);
image1.src = objectURL;

After this the image appears in image1. Next we store it in the cache using add:

var myCache=await caches.open("myCache");
await myCache.add(request); 

Notice that this downloads the response again.

Now we have created the Cache object and stored the request/response pair in it. Next we can retrieve the response from the Cache:

  var response2=await myCache.match(request);
  var blob2 = await response2.blob();
  var objectURL2 = URL.createObjectURL(blob2);
  image2.src=objectURL2; 
}
</script>

If you use the browser to inspect the network traffic you should be able easily confirm that the file is downloaded just twice, once by the fetch and once when it is added to the cache and blob2 is retrieved from disk cache.

Summary

  • New JavaScript APIs tend to use Promises and this means they are best used with async and await.

  • The Fetch and Cache APIs are two good examples and these are fundamental to using the new Service Worker.

  • The Fetch API is a modern implementation of the XMLHttpRequest and it can be used to download almost any file the browser has access to, and to send data to the server using Get or Post.

  • The Fetch API uses Request and Response objects to specify the resource location and represent the response.

  • The cache API is a replacement for appCache.

  • The CacheStorage object stores a set of Cache objects each of which stores a set of key value pairs.

  • A Service Worker is associated with a scope – a range of URLs – and once installed it is active whenever the browser loads a URL in the scope.

  • The Service Worker intercepts all URLs in its scope via the Fetch event.

  • The Service Worker can return a Response object which has been retrieved from a Cache object or it can construct a Response object from scratch. It acts as a proxy server and enables an app to function offline as well as online.

 

Now Available as a Book:

 JavaScript Async

cover

You can buy it from: Amazon

Contents

  1. Modern JavaScript (Book Only)
  2. Events,Standard & Custom
  3. The Callback
      extract - The Callback & The Controller
  4. Custom Async - setTimeout, sendMessage & yield
      extract - Custom Async
      extract - Avoiding State With Yield 
  5. Worker Threads
      extract - Basic Worker ***NEW
      extract - Advanced Worker Threads 
  6. Consuming Promises 
  7. Producing Promises
      extract - The Revealing Constructor Pattern
     
    extract - Returning Promises
     
    extract - Composing Promises
  8. The Dispatch Queue
      extract - Microtasks
  9. Async & Await
      extract -  Basic Async & Await
      extract -  DoEvents & Microtasks
  10. Fetch, Cache & Service Worker
      extract - Fetch  
      extract - Cache
     
    extract -  Service Workers

Also by Ian Elliot 
Just JavaScript: An Idiomatic Approach
Just jQuery: The Core UI 
Just jQuery: Events, Async & AJAX  

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962560>

<ASIN:1871962579>

 <ASIN:1871962528>

<ASIN:1871962501>



Last Updated ( Monday, 06 May 2019 )