本文介绍了如果CDN失败,如何回退到本地样式表(不是脚本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

>
< 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 =stylesheethref =http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min。 css/> 

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



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

解决方案

没有跨浏览器测试,但我认为这将工作。不过,你必须在加载jquery之后,或者你必须用纯Javascript来重写它。

 <脚本类型= 文本/ JavaScript的 > 
$ .each(document.styleSheets,function(i,sheet){
if(sheet.href =='http://code.jquery.com/mobile/1.0b3/jquery.mobile- 1.0b3.min.css'){
var rules = sheet.rules?sheet.rules:sheet.cssRules;
if(rules.length == 0){
$('< ; link rel =stylesheettype =text / csshref =path / to / local / jquery.mobile-1.0b3.min.css/>''.appendTo('head');
}
}
})
< / script>


I am linking to the jQuery Mobile stylesheet on a CDN and would like to fall back to my local version of the stylesheet if the CDN fails. For scripts the solution is well known:

<!-- 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>

I would like to do something similar for a style sheet:

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

I am not sure if a similar approach can be achieved because I am not sure whether the browser blocks in the same way when linking a script as it does when loading a script (maybe it is possible to load a stylesheet in a script tag and then inject it into the page) ?

So my question is: How do I ensure a stylesheet is loaded locally if a CDN fails ?

解决方案

Not cross-browser tested but I think this will work. Will have to be after you load jquery though, or you'll have to rewrite it in plain Javascript.

<script type="text/javascript">
$.each(document.styleSheets, function(i,sheet){
  if(sheet.href=='http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css') {
    var rules = sheet.rules ? sheet.rules : sheet.cssRules;
    if (rules.length == 0) {
      $('<link rel="stylesheet" type="text/css" href="path/to/local/jquery.mobile-1.0b3.min.css" />').appendTo('head');
    }
 }
})
</script>

这篇关于如果CDN失败,如何回退到本地样式表(不是脚本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:18
查看更多