Solved! How to use cache.put to add a jpg to the cache?

57 views Asked by At

This question concerns the javascript cache api.

I have no problem using cache.add to add jpgs to the cache. But so far I have not figured out how to use fetch and cache.put to do the same thing. I have done a lot of searching and skimmed through a lot of posts but so far I have not seen a basic example.

The following code adds jpg_url to the cache as a key. But when my pwa tries to display jpg_url offline, no image is displayed. Apparently my code is not actually saving the jpg in the cache. What am I missing?

Update: Solved! cache_url points to a jpg. The code below will save that jpg in the cache with cache_url as the key. The secret sauce is doing await response.blob()

async function cache_fetch (cache,cache_url) {
    options = {
        method: "GET",
        mode: "cors",
        headers: {'Content-Type': 'image/jpeg'}
    }
    response = await fetch(cache_url, options)
    .then (async function(response) {
        if (response.status === 200) {
            my_blob = await response.blob();
            cache.put(cache_url,new Response(my_blob, {type:'image/jpeg'}))
            .then(function() {
            // do stuff
            })
            .catch(function(error) {
            // do other stuff
            });
        }   else {
            // handle status not 200
        }
    })
    .catch(function(error) {
        // handle fetch error
    });
}           


0

There are 0 answers