【问题标题】:How to check if a <link rel="stylesheet" href="file.css"> succeeded如何检查 <link rel="stylesheet" href="file.css"> 是否成功
【发布时间】:2015-02-15 14:46:29
【问题描述】:

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

在寻找替代方法时,我尝试检查链接语句是否在更改其 href 后加载了新的 css,例如:

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

但它不起作用。

感谢您的建议!

【问题讨论】:

  • 并且简单地使 AJAX 请求异步不是一种选择?
  • 你用的是哪个浏览器,还是所有浏览器都有这个问题?
  • 为什么不检查本地文件是否存在,如果不存在则从服务器加载文件,如果无法获取文件,则表示本地文件不存在,浏览器也不存在已连接到互联网。
  • 或者只是检查浏览器是否可以访问互联网,如果有,则从服务器获取文件,否则搜索本地。

标签: jquery


【解决方案1】:

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

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

<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" />

在这种情况下 custom.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 已加载,因为 custom1111.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 属性来识别要禁用或启用的正确样式表。

更多阅读和示例:

【讨论】:

  • 好主意!从来没有考虑过备用床单。这从根本上解决了问题。现在我来测试一下。
  • 祝你好运,别忘了在我提供的链接中阅读更多内容,你可以用这个概念做更多的事情。
  • "alternate" 很有帮助。我现在使用一个默认值和一个备用值(如果存在)。谢谢!
【解决方案2】:

所以可行的解决方案是输入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 屏幕。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-25
    • 2015-01-14
    • 2017-05-20
    • 2011-09-08
    • 1970-01-01
    • 2013-08-29
    • 2017-02-16
    • 1970-01-01
    相关资源
    最近更新 更多