Provide local fallback for CSS from CDN

后端 未结 1 1486
名媛妹妹
名媛妹妹 2021-01-05 19:27

I\'m loading the Bootstrap CSS on my page from the CDN bootstrapcdn.com



        
1条回答
  •  醉梦人生
    2021-01-05 20:16

    This is what I have created for our needs. If this meets your needs, simply call the function ensureCssFileInclusion(file to check, boolean value). You will have to adjust it for your needs to make sure that you provide the cssFileToCheck, fallbackCssFile in this function.

    /**
     * Checks the page for given CSS file name to see if it was already included within page stylesheets.
     * If it was, then this function does nothing else. If CSS file was not found among page stylesheets,
     * then this function will attempt to load the stylesheet by adding an HTML link tag to the document
     * HEAD section. You must also specify whether given cssFileToInclude is a relative path or an absolute path.
     */
    ensureCssFileInclusion = function(cssFileToInclude, isRelativePath) {
       if (isRelativePath) {
         if (!window.location.origin) {
            cssFileToInclude = window.location.protocol+"//"+window.location.host + cssFileToInclude;
         }
       }
       var styleSheets = document.styleSheets;
       for (var i = 0, max = styleSheets.length; i < max; i++) {
         if (styleSheets[i].href == cssFileToInclude) {
            return;
         }
       }
       // because no matching stylesheets were found, we will add a new HTML link element to the HEAD section of the page.
       var link = document.createElement("link");
       link.rel = "stylesheet";
       link.href = cssFileToInclude;
       document.getElementsByTagName("head")[0].appendChild(link);
    };
    

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