Use local files if CDN is Offline

Asked

Viewed 303 times

9

I wonder if it is possible to perform a callback if a CDN is offline the system uses local files.

Ex: I use the Fontawesome CDN but if the user runs out of the internet or the CDN goes offline, it is possible to create a callback for the system to use local files.

obs. The system should give preference to the use of CDN if it is online and the user has internet.

  • By "local file" you mean "browser cache"?

  • No, for example, I have the CDN call and also the local file call <link src="fontawesome.min.css"> if the CDN fails the local file is called.

1 answer

5


Yes. I’ll give you an example with jQuery loaded on Google CDN.

In the head of your HTML, you should add the CDN script:

<head>
    <!-- ... -->
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

In the body, add a code to verify if the $ defined, and if not, add the "fallback" script to be loaded:

<script>
    if ( typeof $ === "undefined" ) {
        var s = document.createElement("script");
        s.type = "text/javascript";
        s.src = "//servidor.com.br/jquery-1.11.3.min.js";
        document.body.appendChild(s);
    }
</script>

Just don’t forget that if you have scripts that require jQuery, they should be loaded dynamically after jQuery is loaded, following the same logic above.

  • 1

    That’s what I needed, I just didn’t know how to do it, I’m a beginner in jQuery and I had seen something like that somewhere, but at the time I didn’t care. thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.