Kalnode
Kalnode

Reputation: 11296

Does a service worker cache work site-wide, even without loading an HTML with sw.js?

Does a service worker cache work site-wide, regardless whether the user is actually on an HTML page that has sw.js loaded?

For example: Assuming...

If the user were to directly visit any of those JPG or CSS files in their browser, does the browser run the request through the service worker and/or on it’s own recognize those local files, and thus render the locally cached file?

Upvotes: 0

Views: 79

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

One a service worker is activated, its fetch handler will be triggered whenever there is:

  • A navigation to a URL under the service worker's scope.
  • A request for a URL made by a client page that's under the service worker's scope. (Such as a request for an image, or stylesheet, etc.)

If you were to navigate directly to a URL that exists under the service worker's scope, even if that URL didn't correspond to an HTML document, the service worker's fetch handler would have a chance to respond.

If your service worker has a fetch handler that always responded with a cached version of a given URL, then yes, that response would be used to fulfill the navigation, even if the asset was an image or stylesheet or something else.

You can test this out for yourself:

  1. Visit a site like https://images.guide/ that installs a service worker, caches a number of resources, and uses a fetch handler that responds to requests for precached resources via the cache.
  2. Go offline.
  3. Navigate to a URL that's precached, like https://images.guide/images/hamburger.svg

You'll see that the precached resource is used to respond to the navigation request.

Upvotes: 1

Related Questions