Cache Third Party Resources from a CDN in a React PWA

Share this video with your friends

Send Tweet

Our service worker caches our static assets - but only those assets that are included in our React App. This means that assets like Bootstrap, which we're including from a third-party CDN, won't be included in the cache, because they're not available at webpack compile time.

We'll change the service worker to add caching for those assets by using workbox's registerRoute method, and a regular expression to match the entire URL of the asset. We'll pick the staleWhileRevalidate cache strategy, though cacheFirst, or networkFirst would also be valid choices.

Finally, we'll change the name of the cache they are stored by supplying a cacheName parameter.

Pavel Klochkov
Pavel Klochkov
~ 6 years ago

Hi, thanks for the interesting and very valuable course. Here is a small problem in lesson 7. You use RegExp with https, but in the code example on GitHub most of resources are served from http. And caching does not work for them. So it works with

'http:.*min\.(css|js)'

or

'(http|https):.*min\.(css|js)'

Maybe there is a reason to change example code on GitHub to use https links?

Chris Achard
Chris Achard(instructor)
~ 6 years ago

The resources I'm trying to cache with that line are the ones from the cdn in index.html - and it appears that they are all being served from https, so I believe that line should work... what resources are you seeing that aren't being cached?

Pavel Klochkov
Pavel Klochkov
~ 6 years ago

Hi Chris. I need to say sorry. I checked code for all of your lessons and everything is fine. Maybe I copied code from GitHub in a wrong way. Thank you again for the awesome course! I've just implemented SW and cache for resources and responses in one of my projects.

Chris Achard
Chris Achard(instructor)
~ 6 years ago

No problem - I'm glad it worked!

Alexander Esser
Alexander Esser
~ 6 years ago

The reason for the http/https problem might be in the transcript of lesson 2 which uses http links in the index.html and not https.

Chris Achard
Chris Achard(instructor)
~ 6 years ago

Ah, great catch Alexander! I will need to make sure that transcript changes to include the https.