ServiceWorker缓存完成要求

时间:2018-11-22 08:47:21

标签: javascript caching fetch service-worker

如何使ServiceWorker缓存已完成的请求?我尝试了以下方法:

//If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener('fetch', function(event) {
//Trying to answer with "online" version if fails, using cache.
event.respondWith(
    fetch(event.request).then(function (response) {
    //Checking if url is market as noCache
    if(noCache.contains(request) { // <- Pseude code checking wether to cache
        console.log('mtSW: Adding file to cache: '+response.url);
        caches.open(appVersion+'-offline').then(function(cache) {
            cache.put(new Request(response.url), response.clone());
        });
    }
    return(response);
    }).catch(function(error) {
    console.log( 'mtSW: Error fetching. Serving content from cache: ' + error );

    //Check to see if you have it in the cache
    //Return response
    //If not in the cache, then return error page
    return caches.open(appVersion+'-offline').then(function (cache) {
        return cache.match(event.request).then(function (matching) {
        var report =  !matching || matching.status == 404?Promise.reject('no-match'): matching;
        return report
        });
    });
    })
);
})

包含的行

cache.put(new Request(response.url), response.clone());

不起作用。

如何使ServiceWorker缓存此请求?

0 个答案:

没有答案