0

Assume that a service-worker.js is ready to offer offline browsing ability thanks to the following code,

self.addEventListener("fetch", event => {
  event.respondWith( caches.match(event.request).then( cachedResponse => {   return cachedResponse || fetch(event.request);   } )  );
});

And let's say we have cached some assets where the files are listed relative to the root directory,

const cacheAssets = await caches.open('necessary-files-v1');
const listOfFiles = [
    "/somefolder/somepage.html",
    "/somefolder/somevisual.jpg",
    "/somefolder/someaudio.mp3"
];
await cacheAssets.addAll(listOfFiles);

Now compare the offline case for the following two (obviously they both work fine when online),

Scenario 1: somepage.html contains <img src="somevisual.jpg">

Scenario 2: somepage.html contains <img src="/somefolder/somevisual.jpg">

Given the fact that the string to string comparison ("somevisual.jpg" == "/somefolder/somevisual.jpg") will return false should we always and always adopt Scenario 2 when building our html files with the hope of offline compatibility? Or is there a case or some method that offers us developers some nice-to-have flexibility?

HolyResistance
  • 594
  • 1
  • 8
  • 26
  • Looks like this question is somewhat related, https://stackoverflow.com/questions/57205580/can-the-service-worker-access-browser-cache?rq=1 – HolyResistance Aug 17 '23 at 15:04
  • In case you want to know about the benefits of using service workers, https://stackoverflow.com/questions/36916074/why-use-a-service-worker-for-caching-when-browser-cache-handles-the-caching – HolyResistance Aug 17 '23 at 15:06

1 Answers1

0

I'm not sure you need to make a string comparison; and I don't see that happening in your code. I believe the nice-to-have flexibility that you're looking for should be built in to the browser APIs (cache.addAll and fetch) and Request object; string URLs can be converted into Request objects for comparison.

For example, cache.addAll invokes the Request constructor on each of the strings you pass in, and you're passing in a Request to caches.match (as event.request). So the actual matching algorithm should be comparing something more like Request("/somefolder/somevisual.jpg") to Request("somevisual.jpg") (from event.request in the fetch event) rather than a string comparison like ("somevisual.jpg" == "/somefolder/somevisual.jpg"). I would think the former should generally account for the different paths, though I imagine there could still be edge cases to consider like query parameters.

Does this not work when you test?

As an aside, I see you aren't opening the cache, as in this example, which may be causing you troubles (I'm not sure though, I haven't used these API's in years).

David
  • 2,846
  • 3
  • 22
  • 34