Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching external resources with sw-precache

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?

like image 349
zeosamaster Avatar asked Dec 24 '22 23:12

zeosamaster


1 Answers

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:

  1. 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.

  2. 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.

like image 51
Jeff Posnick Avatar answered Jan 13 '23 11:01

Jeff Posnick