HTML if statement to load local JS/CSS upon CDN failure

前端 未结 2 1038
甜味超标
甜味超标 2021-02-09 05:45

When loading a CSS/JS file from CDN or any external server, it is possible (even with low probability) to miss the file due to external failure. In this case, the html page will

相关标签:
2条回答
  • 2021-02-09 06:10

    I would do it this way.

    Create a class within your stylesheet ui-helper-hidden and then add a div as the first element on your page;

    <body><div class="ui-helper-hidden"></div><!-- rest of html --></body>
    

    After you have checked to make sure your CDN javascript file has been loaded, then use this bit of code note i am using jquery

    <script>
        // CSS Fallback
        $(function () {
            if ($('.ui-helper-hidden:first').is(':visible') === true) {
                $('<link rel="stylesheet" type="text/css" href="/pathtocss/nameofstylesheet.css" />').appendTo('head');
            }
        });
    </script>
    

    This will check to see if the element which should be hidden is or not. If it isnt hidden, then you know your css file has not loaded from the CDN.

    I use this method for jQuery and jQuery UI via a CDN

    0 讨论(0)
  • 2021-02-09 06:31

    For Javascript, you can listen for the onload and onerror events when building a dynamic script. However, in those same pages, it shows otherwise for CSS.

    The only reliable way to dynamically load CSS is to do it via AJAX. You could load the styles via dynamic link tags but without those events, you won't know if they have been loaded at all. You could poll for the styles, but it's hackish IMO.

    Another way to do it is make the server read those CDN files. If they're good, print the urls for the links. But if those links are dead, make it print the local urls instead. This would be more reliable, and offloads your logic to the server. This assumes that you have access to the server.

    Or better, use the local versions in the first place! With good caching, bandwidth won't be an issue

    0 讨论(0)
提交回复
热议问题