How to load local static files if CDN fails without using document.write()?

114    1 year ago

What I am trying to accomplish

I will be hosting a web application on a LAN for about 50 people at the maximum. No one from outside the LAN will be accessing the web server. Right now I have the web application using CDNs to deliver Bootstrap and jQuery amongst a few other things. I would like to have the web application fallback to local static copies of the CDN files in case something goes wrong.

My question

  1. If my web server is only being used by users on a LAN, which method is better: a CDN or local files?
  2. How do I fallback on local files without using document.write()?

NOTE: I'm not trying to accomplish this only for jQuery. I would like to do this for several files.

Related SO questions

I have looked at the dozens of other questions that answer what I'm trying to do, the most popular are listed below.

  1. Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
  2. How to load local script files as fallback in cases where CDN are blocked/unavailable?
  3. Is Google’s CDN for jQuery available in China?

What I have attempted

I implemented the following code from question (1)

<!--<script type="text/javascript" src=""></script>-->
     console.log(window.jQuery) // ==> undefined
     window.jQuery || document.write('<script type="text/javascript" src="{% static "js/jquery-3.4.1.min.js" %}"><\/script>');
     console.log(window.jQuery) // ==> undefined

but this solution:

  1. fails to load the document
  2. causes Google Chrome DevTools to state the following
[Violation] Avoid using document.write().
[Violation] Parser was blocked due to document.write(<script>)

This then led me to the SO question titled A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?. I then tried to implement the accepted solution and appended async to my code like so

   console.log(window.jQuery) // ==> undefined
   window.jQuery || document.write('<script type="text/javascript" src="{% static "js/jquery-3.4.1.min.js" %}" async><\/script>');
   console.log(window.jQuery) // ==> undefined

but it still fails to load the document and I get the following error again:

[Violation] Avoid using document.write().

In conclusion

So what is the right way to accomplish this? How do I do this without using document.write()? It seems like the answers to the previous questions are now outdated.

Answers { 1 }
1 year ago

You should listen to the onerror event, if it occurs then load the local one.
Here is an example (you should change the code to fit your case):

    function onJqueryLoadError()
        document.write('<scr' + 'ipt src="static/jquery-3.4.1.min.js"></scr' + 'ipt>');
<script src="https://www.cdn/jquery-3.4.1.min.js" onerror="onJqueryLoadError()"></script