Search code examples
service-workercdnprogressive-web-apps

Cherry-pick: from two URLs with same file on different CDNs, load whichever is in cache


I have a web app that wants to load bootstrap.min.js

It's on these two CDN's (among others):

https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js

The odds of a cache hit from some other app using these CDN's is relatively high.

How can I tell the browser to check if they are cached and load from browser cache?

Can a service worker do this?


Solution

  • I believe that there are some privacy/security restrictions in place that attempt that make it difficult to determine, using JavaScript, whether a third-party URL is present in the browser's cache.

    Adding a service worker into the mix will not get around those restrictions.

    It's possible to use the Fetch API to create a Request with a mode of 'only-if-cached', which will behave more or less in the way you describe, but that will only work if the request's mode is 'same-origin'. In other words, only if the Request is for a first-party URL, not a third-party CDN URL as in your example.