Search code examples
htmlsrcfallbackonerror

HTML src onerror doesn't load fallback in time


I have the following code in my HTML file:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"
 onerror="this.onerror=null;this.src='../js/axios.min.js?v=0.26.1';"></script>

What it supposed to do, if the primary source src (the CDN) fails, it should load the fallback script onerror from my server, as a fallback solution.

But when I purposely put a typo in the first source to test it, the content part of my webpage would not load since it can't load the script (Axios), and my whole page relies on that. However in the F12 Console I can see that the right fallback file is loaded afterwards.

So I guess what happens, is that because of the primary source src can't be loaded, it loads the fallback source onerror, but it takes a little time to "switch", and meanwhile the loading of the other parts of the HTML is ongoing. So it doesn't wait until the fallback source file is loaded.

If that's right, my question is: How can I make the site loading wait until the fallback source is loaded in case of error with the primary source? Because without this script my site won't work at all, so useless to go on loading without it.

Thank you.

UPDATE #1: Maybe if I add both (CDN and own server) variants at the same time?

<script
src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"</script>
<script src="../js/axios.min.js?v=0.26.1"></script>

FYI: I must have the CDN variant there, I can't remove it. But I need a fallback solution if that fails to load. So maybe this is an acceptable solution.

What do you think? Any drawbacks?

Thank you.


Solution

  • I found a working solution:

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      if (typeof axios == 'undefined') {
        document.write(unescape("%3Cscript src='../js/axios.min.js?v=0.26.1' type='text/javascript'%3E%3C/script%3E"));
      }
    </script>
    

    Maybe it will be useful for somebody as well.

    Thank you.