本文介绍了< link> onerror在IE中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 onerror 事件(404错误)的事件处理程序附加到< link> 元素。

I am trying to attach an event handler for the onerror event (404 error) to a <link> element.

我的页面上有这样的内容:

I have something like this on my page:

<link rel="stylesheet" type="text/css" href="dead/link.css" onerror="handle404Error()" />

在Chrome和Opera上运行良好,但在IE9 +上也应运行。我找到了,但是我自己找不到解决方案。

It works fine on Chrome and Opera but it should work on IE9+ too. I found this, but I can't find a solution myself.

是否可以做到这一点而无需编写额外的方法来动态加载样式?

Is there a way to do that without writing an extra method to load styles dynamically?

注意:我没有用'jquery'标记此问题,所以请不要在答案中使用它。

NOTE: I didn't tag this question with 'jquery', so please don't use it in your answers.

推荐答案

在IE中, onerror 事件不会在无效的链接网址,但 onload 事件可以。

In IE, the onerror event does not fire on invalid link URLs, but the onload event does.

在Chrome中,情况恰恰相反: onload 事件不会在无效的 link 网址上触发,但 onerror

In Chrome, the opposite is true: The onload event does not fire on invalid link URLs, but the onerror event does.

所以您需要同时使用两个事件:

So you'll need to use both events:

<link rel="stylesheet" type="text/css"
      href="dead/link.css"
      onload="handle404Error(this)"
      onerror="handle404Error(this, true)"
/>

function handle404Error(el, failed) {
  if(failed || (el.sheet.cssRules && !el.sheet.cssRules.length)) {
    //Failed!
  }
  else {
    //Success!
  }
}



示例使用无效的URL:




使用有效URL的示例:

http://jsfiddle.net/et0g2xg6/1

更新于2017年8月,感谢@Alex:

这篇关于&lt; link&gt; onerror在IE中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:59
查看更多