从CDN提供CSS的本地回退 [英] Provide local fallback for CSS from CDN

查看:159
本文介绍了从CDN提供CSS的本地回退的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从CDN bootstrapcdn.com 在我的网页上加载Bootstrap CSS

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

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

如何测试样式表是否已加载,如果不提供本地回退?

How can I test if the stylesheet was loaded, and if not provide a local fallback?

不要想等待jQuery或其他库加载测试之前;我希望所有的CSS首先加载到页面上。

I do not want to wait for jQuery or other libraries to load before doing the test; I want all CSS to be loaded on the page first.

推荐答案

这是我为我们的需要创建的。如果这满足您的需要,只需调用函数ensureCssFileInclusion(要检查的文件,布尔值)。您必须根据您的需要调整它,以确保您在此函数中提供cssFileToCheck,fallbackCssFile。

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);
};

这篇关于从CDN提供CSS的本地回退的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆