html - 如果 CDN 失败,如何回退到本地样式表(不是脚本)

标签 html jquery css jquery-mobile cdn

我正在链接到 CDN 上的 jQuery Mobile 样式表,如果 CDN 失败,我想回退到我本地版本的样式表。对于脚本,解决方案是众所周知的:

<!-- Load jQuery and jQuery mobile with fall back to local server -->
<script src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
<script type="text/javascript">
  if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='jquery-1.6.3.min.js'%3E"));
  }
</script>

我想为样式表做类似的事情:

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" />

我不确定是否可以实现类似的方法,因为我不确定浏览器在链接脚本时是否以与加载脚本时相同的方式阻塞(也许可以在脚本中加载样式表标记,然后将其注入(inject)页面)?

所以我的问题是:如果 CDN 失败,如何确保在本地加载样式表?

最佳答案

可以使用 onerror为此:

<link rel="stylesheet" href="cdn.css" onerror="this.onerror=null;this.href='local.css';" />

this.onerror=null; 是为了避免无限循环,以防万一它自己的回退不可用。但它也可以用于多个回退。

但是,这目前仅适用于 Firefox 和 Chrome。

更新:同时,这似乎是supported by all common browsers .

关于html - 如果 CDN 失败,如何回退到本地样式表(不是脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7383163/

相关文章:

无图像网页设计的性能提升

html - 为什么带有 { flex : 1; width: 0; } still have width? 的元素

html - Rails HTML 转义纯文本电子邮件

python - BeautifulSoup : Parsing "Span" element

javascript - 如何自动选择多选框chzn-select-deselect?

javascript - 如何将 jquery 代码转换为可重用的插件/函数

jquery - 如何检测是否按下了 Ctrl+R?

HTML anchor ,禁用样式

html - 为类的所有实例设置样式,但在 CSS 中选择的除外

jQuery css() 无法使用可见性