如何检查 <链接 rel= "stylesheet" href= "file.css" >是否成功



我正在为js应用程序添加主题设置。应用程序也应该离线工作,所以我必须检查远程样式文件(如http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/jquery/jquery-ui.css)是否存在并且可以访问,否则我将<link rel="stylesheet">中的href设置为指向本地文件。

到目前为止,我使用了以下代码,但在jQuery 2.1.3中,它在控制台上输出了一个警告:

主线程上的同步XMLHttpRequest已被弃用,因为它会对最终用户的体验产生有害影响。有关更多帮助,请查看http://xhr.spec.whatwg.org/.

jquery-2.1.3.js:8556行引发的嗯,我可以忽略这个警告。。。

url = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/jquery/jquery-ui.css";
$.ajax({url: url,
    type: "HEAD",
    timeout: 1000,
    async: false,
    error: function() {url = 'css/jquery-ui.css';}
});
/* modify link statement to use url for href */

为了寻找另一种方法,我试图检查link语句在更改href后是否加载了新的css,比如:

$('#id_of_the_link_stmt').error(function() {
  console.log("New url not loaded, reverting to local file")
}).attr('href', url);

但它不起作用。

谢谢你的建议!

为什么不使用替代样式表和组?

您可以始终包含基本样式表和自定义样式表作为备用样式表:

<link rel="stylesheet" type="text/css" href="css/base.css" title="base" />
<link rel="alternate stylesheet" type="text/css" href="css/custom.css" title="base" />

在这种情况下,customer.css可用,浏览器会加载他(只有他)-如果不可用,浏览器将移动到第一个(没有备用)并加载他-例如:

<link rel="stylesheet" type="text/css" href="css/base.css" title="base" />
<link rel="alternate stylesheet" type="text/css" href="css/custom11111.css" title="base" />

现在加载了base.css,因为custom111.css不可用。

请注意,组是由title属性定义的-您也可以设置许多组-例如:

<link rel="stylesheet" type="text/css" href="css/main.css" title="base" />
<link rel="alternate stylesheet" type="text/css" href="css/main_custom.css" title="base" />
<link rel="stylesheet" type="text/css" href="css/nav.css" title="nav" />
<link rel="alternate stylesheet" type="text/css" href="css/nav_custom.css" title="nav" />

使用JavaScript切换样式表:

可以通过将样式表设置为disabled = true来禁用样式表。使用title属性来标识要禁用或启用的正确样式表。

更多阅读和示例:

  • 替代CSS样式/主题
  • 如何使用JavaScript动态更改级联样式表(CSS)

因此,有效的解决方案是放入index.html:

<link rel="stylesheet" href="css/jquery-ui.css" title="theme"/>
<link rel="alternate stylesheet" id="ui-theme" title="theme"
      href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/dark-hive/jquery-ui.css"/>

在主题变更代码中:

url = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/"+theme_name+"/jquery-ui.css";
$('#ui-theme').attr('href', url);

因此,如果用户处于脱机状态,jquery-ui.css的本地副本就会启动,并且她不会面临未格式化的jQuery UI屏幕。

最新更新