Ranko Kuljanin
Ranko Kuljanin

Reputation: 31

ServiceWorker Prefetching with absolute URLs

I have a service worker (used for caching resources) on my site at https://example.com with a scope of /app-1.

example.com
- /images/image.jpg
- /css/style.css
- /app1

What I know from documentation is that service worker cannot access ../images/image.jpg or ../css/style.css because it can access only subpaths of the scope.

I went boldly and added absolute paths to my service worker for it to cache:

var urlsToPrefetch = [
 './',
 'https://example.com/css/style.css',
 'https://example.com/images/image.jpg'
];

And that somehow works, so now Cache Storage shows:

https://example.com/app1
https://example.com/images/image.jpg
https://example.com/css/style.css

Exactly what it should. There are no errors whatsoever.

Can anyone, please, confirm that this approach is acceptable and explain why (considering scope restrictions).

Upvotes: 1

Views: 860

Answers (1)

Richard Connon
Richard Connon

Reputation: 360

Slight confusion here by what Serivce Worker Scope really means. It is used to specify the subset of your content that you want the service worker to control, not fetch.

As in Service Worker is installed upon a page that is in scope, it is then perfectly able to fetch the resources in the URL and cache them. The only issue being if any of these resources that are out of scope are pages that you wish to nagivate to, the Service Worker will not be installed on that page so you best plan for that loss in functionality.

One last thing is that if you put the Service Worker file at the root of the project, all content under the app's origin will be in scope. So should you put the Service Worker file at the root, then "/images/image.jpg" will be in scope.

Upvotes: 3

Related Questions