繁体   English   中英

Javascript服务工作者:从缓存中获取资源,但也进行更新

[英]Javascript service worker: Fetch resource from cache, but also update it

我在chrome上使用服务工作者来缓存网络响应。 客户端请求资源时我打算做什么:

检查缓存-如果存在,请从缓存中返回,如果文件与缓存版本不同,则还向服务器发送请求并更新缓存。 如果没有缓存,则将请求发送到服务器,然后缓存响应。

这是我目前执行此操作的代码:

self.addEventListener('fetch', function (event) {
    var requestURL = new URL(event.request.url);
    var freshResource = fetch(event.request).then(function (response) {
        if (response.ok && requestURL.origin === location.origin) {
            // All good? Update the cache with the network response
            caches.open(CACHE_NAME).then(function (cache) {
                cache.put(event.request, response);
            });
        }
        // Return the clone as the response would be consumed while caching it
        return response.clone();
    });
    var cachedResource = caches.open(CACHE_NAME).then(function (cache) {
        return cache.match(event.request);
    });
    event.respondWith(cachedResource.catch(function () {
        return freshResource;
    }));
});

该代码不起作用,因为它会引发错误:

网址的FetchEvent导致网络错误响应:将不是响应的对象传递给responseWith()。

谁能指出我正确的方向?

好的,在人们指出建议(谢谢您)并找到解决方案之后,我摆弄了代码。

self.addEventListener('fetch', function (event) {
    var requestURL = new URL(event.request.url);
    var freshResource = fetch(event.request).then(function (response) {
        var clonedResponse = response.clone();
        // Don't update the cache with error pages!
        if (response.ok) {
            // All good? Update the cache with the network response
            caches.open(CACHE_NAME).then(function (cache) {
                cache.put(event.request, clonedResponse);
            });
        }
        return response;
    });
    var cachedResource = caches.open(CACHE_NAME).then(function (cache) {
        return cache.match(event.request).then(function(response) {
            return response || freshResource;
        });
    }).catch(function (e) {
        return freshResource;
    });
    event.respondWith(cachedResource);
});

整个问题源于在缓存中不存在该项目并且cache.match返回错误的情况。 我需要做的就是在这种情况下获取实际的网络响应(Notice return response || freshResource

这个答案就是Aha! 对我来说是关键的时刻(尽管实现方式有所不同): 仅在脱机时使用ServiceWorker缓存

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM