I'm trying to get sw-precache
to pre-cache external CDN resources, but the generated service-worker.js doesn't contain the CDN url's in the precacheConfig
array.
This is what I have in my gulpfile
:
staticFileGlobs: [
'http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css',
'client/assets/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff,ico}'
]
The files inside my local client/assets
folder are added to the precacheConfig
array, but the external font-awesome css isn't. Is there a way to achieve this?
sw-precache
can only precache and keep up to date local assets, like those that match the client/assets/**/*...
pattern you're using. It's not meant to work with remote assets that are accessed via CDN.
You have a couple of approaches:
Use npm
(or the package manager or your choice) to download a local copy of the resource (i.e. font-awesome) and then deploy that third party resource alongside your first-party assets. If the third-party code is picked up by a pattern you pass to staticFileGlobs
then it can be precached and versioned just like anything else local.
Use runtime caching to handle the resource on the CDN. Since the URL for your specific asset includes a 4.0.3
versioning string, it's safe to assume that the underlying contents will never change, and a cacheFirst
strategy is probably safe.
You can modify your sw-precache
configuration to look like the following:
{
staticFileGlobs: [
'client/assets/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff,ico}'
],
runtimeCaching: [{
urlPattern: /^https:\/\/netdna\.bootstrapcdn\.com\//,
handler: 'cacheFirst'
}],
// ...any other config options...
}
That configuration is broad enough to pick up anything served off that CDN, cache it, and then serve it cache-first once in subsequent visits.
Please note that your example used an http:
protocol for your CDN's URL, and you'll need to use https:
to obtain a response that plays nicely with service worker caching.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With