Link to home
Start Free TrialLog in
Avatar of John S.
John S.Flag for United States of America

asked on

How to load CDN if available, if not load local script?

Recently a CDN we used went down, and our site malfunctioned.

Is there a way, using script, we can use the CDN if it's available ( if we don't get a 404 for example ), and if it's not, use a local version of our script?

Thanks!

John
Avatar of ste5an
ste5an
Flag of Germany image

You may take a look like solutions like http://fallback.io/.

But the simple approach: test for a variable declared by your scripts. When they don't exist, load your local version.
ASKER CERTIFIED SOLUTION
Avatar of David S.
David S.
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Or you can simply self host all scripts.

If your site caching is correctly setup then server load will be minimal.

If you're running HTTP/2, then all resources begin serving at same time, so the entire supposed purpose of CDNs only makes sense if you're running the old HTTP/1.1 protocol.

If you self host + your site dies... well nothing lost...

If you use a CDN, even with a fallback strategy, to verify this is working will require you continually test your fallback.

The way you do testing, depend on your code. Likely test method is to set all CDN hosts/domains to 127.0.0.1 in your local caching DNS setup.

This will force all CDN references to return 404s for all assets + cause your fallback mechanism to exercise.

If you use a fallback approach, be sure + test it every day (continual mechanical test), to ensure your fallback mechanism is working all the time.
Hi,
I never (rarely) use external file for security reason.
If you do so make sure that the link have  integrity="sha...."

for example:
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Open in new window


For more information
https://www.troyhunt.com/the-javascript-supply-chain-paradox-sri-csp-and-trust-in-third-party-libraries/
Avatar of John S.

ASKER

Thank you all. Very helpful.
You're welcome.

To add to what Lena said, CDNs are especially useful for hosting popular JS and CSS frameworks/libraries. Why load the same file from each site that uses it?

As to the security implications of that, you can use Subresource Integrity (SRI).

https://hacks.mozilla.org/2015/09/subresource-integrity-in-firefox-43/