最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Serving images from device cache (web app) - Stack Overflow

programmeradmin0浏览0评论

I have a go / htmx stack app that is serving images from s3 with a cloudfront distribution in front. I am attempting to load images from a service worker and store them in a cache then serve them from the cache if they exist there before sending an actual network request to cloudfront. The images are requested via an img src tag via the application code. The service worker currently is successful in storing these images in the cache, but the screenshot here is confusing as it's leading me to believe that the image is being requested from cloudfront again.

I am unable to log any response from the following service worker code. I am only pasting the "fetch" listener code of the service worker as it is the relevant code:

self.addEventListener('fetch', event => {
  if (event.request.destination === 'image' && event.request.url.includes("cloudfront")) {
    event.respondWith(
      caches.match(event.request)
        .then(response => {
          // Return the cached image if available, otherwise fetch from network
          console.log(response)
          return response || fetch(event.request).then(networkResponse => {
            // Cache the new image and return it
            const responseClone = networkResponse.clone();
            caches.open(CACHE_NAME).then((cache) => {
              cache.put(event.request, responseClone);
            });
            return networkResponse;

          });
        }).catch((err) => {
          // Fallback image if network fetch fails and not in cache
          console.log("not in: ", err)
          return;
        })
    );
  }
});

I would expect to see (disk cache) or (memory cache) next to the images fetched by the service worker.

发布评论

评论列表(0)

  1. 暂无评论