6

CDN bootstrapcdn.comから自分のページに Bootstrap CSS をロードしています。

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">

スタイルシートが読み込まれたかどうかをテストするにはどうすればよいですか?そうでない場合は、ローカル フォールバックを提供しますか?

テストを行う前に、jQuery やその他のライブラリがロードされるのを待ちたくありません。すべての CSS を最初にページにロードする必要があります。

4

1 に答える 1

3

これは、私たちのニーズに合わせて作成したものです。これでニーズが満たされる場合は、関数 ensureCssFileInclusion(チェックするファイル、ブール値) を呼び出すだけです。この関数で cssFileToCheck、fallbackCssFile を提供するように、必要に応じて調整する必要があります。

/**
 * 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);
};
于 2013-07-02T23:30:05.083 に答える