【问题标题】:Provide local fallback for CSS from CDN从 CDN 为 CSS 提供本地回退
【发布时间】:2013-06-30 12:08:43
【问题描述】:

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

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

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

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

【问题讨论】:

  • 这可能具有挑战性,因为我认为 CSS 是异步加载的。
  • 你不希望加载JQuery或其他资源,但我下面分享的代码是纯javascript代码,对jQuery没有任何依赖(我认为)。如果不使用 javascript,我不知道有任何其他方法可以实现您正在寻找的东西。当然,除非对 w3 规范进行某种修订,您可以在其中指定回退库——我认为这将是未来对规范的一个非常好的更新。

标签: javascript css cdn


【解决方案1】:

这是我为我们的需要而创建的。如果这满足您的需求,只需调用函数 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);
};

【讨论】:

  • 这是否可以跨浏览器正常工作?页面加载时间有什么问题吗?
  • 我们现在处于预生产阶段,但是这个功能已经使用了大约一年,我们还没有看到任何让我们担心的东西。我总是提醒那些关心(或尝试优化)像这样的 30ms 进程的人的一件事是......无论如何,我们向客户端机器划拨了太多垃圾(javascripts/css/images)等,这 20 /30 毫秒不会改变任何事情。其次,如果在服务于数百万客户的服务器上这是 20/30 毫秒,我可能会考虑它,但是具有多核处理器和 4+GB RAM 的现代客户端能够处理这个问题。
  • 关于您的问题“这是否可以跨浏览器正常工作?”...它是纯 javascript,所以只要您使用支持 javascript 的浏览器,我不明白为什么这行不通!
  • 出于好奇,这段代码在哪些方面比&lt;link rel="stylesheet" href="cdn.css" onerror="this.onerror=null;this.href='local.css';" /&gt; 更好? (当时可能不存在,只是要求当前使用)
猜你喜欢
  • 2013-07-06
  • 2014-01-14
  • 2012-11-03
  • 2013-07-08
  • 2014-11-25
  • 2012-11-19
  • 1970-01-01
  • 2014-10-27
  • 2015-09-22
相关资源
最近更新 更多