最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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.

Post a comment

comment list (0)

  1. No comments so far