Javascript – Providing Local JS and CSS Resources for CDN Fallbacks

cdncssjavascript

Given that

  • CDNs are a Good Thing because they can serve resources closer to the client, the client can cache them, and you can reduce load on your own server.
  • In recent browsers, loading resources from third-party servers does not decrease security thanks to Subresource Integrity (SRI).
  • CDNs may be down or blocked in some countries, and are not available when developing offline1.

I think it is compelling to use CDNs, but also to be prepared for them to be unavailable. This blog post gives a nice introduction to different approaches for providing fallbacks. If you look at the Basic example, you can see that it already contains quite a bit of boilerplate code to provide fallbacks for just jQuery and Bootstrap, while the favored solution suggests using Fallback.js, which seems to be largely unmaintained for the past year. Similarly, the most relevant SO question for the topic is only about providing a fallback for jQuery.

However, in most real-world projects, I would expect to have 5 or more js/css resources, so I feel like you shouldn't have to repeat some messy boilerplate to provide fallbacks for all of them. Furthermore, every time you add or update a resource, you now have to

  • Update the CDN link
  • Update the local fallback copy by manual download or changing version in npm/bower config
  • Update the link to the fallback
  • Update the SRI hash

Whereas in the Ideal World, I would expect to add/update the resource in one configuration file, and have all the other steps execute automatically (and then run tests to see if the update broke anything).

Is there already an established workflow to achieve this?

Or are CDNs, and especially SRI, still too recent?

Or do most people simply not care to provide fallbacks for CDN resources?


1. Although you could have a dev build that doesn't rely on CDNs, but I also consider that a form of fallback, since it also needs to be maintained.

Best Answer

I think you perhaps misunderstand how larger sites which might need this kind of resilience use CDNs.

it's not just a matter of hosting jQuery or some images. The majority of the site will be hosted on the CDN, with only dynamically generated things like payment pages or shopping baskets being hosted on the 'primary webfarms'

Even these are moving more and more to being processed locally with JS and cookies to display user specific stuff without hitting server side processing.

If a CDN fails and you start getting all the traffic passed to your webserver, it is likely to fall over, otherwise you didn't really need the CDN.

Related Topic