<link> onerror 在 IE 中不起作用

<link> onerror do not work in IE

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

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

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

它在 Chrome 和 Opera 上工作正常,但它也应该在 IE9+ 上工作。我找到了 this,但我自己找不到解决方案。

有没有一种方法可以在不编写额外的方法来动态加载样式的情况下做到这一点?

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

在 IE 中,onerror 事件不会在无效的 link URL 上触发,但 onload 事件会触发。

在 Chrome 中,情况正好相反:onload 事件不会在无效的 link URL 上触发,但 onerror 事件会触发.

因此您需要同时使用这两个事件:

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

http://jsfiddle.net/et0g2xg6/


示例使用有效 URL:

http://jsfiddle.net/et0g2xg6/1

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

onerror is fired by Chrome and Firefox.
onload is fired by Internet Explorer.
Edge fires neither onerror nor onload.

以下解决方案在 Firefox 中有效,您只需要安排函数定义和函数调用:

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

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

IE 当 link href 用于无效域 url 时,例如不是 404,然后 IE 在尝试访问 cssRules 属性.

时抛出 Access is denied
function load (e) {
  var cssRules;
  try {
    cssRules = e.target.sheet && e.target.sheet.cssRules;
  } catch (e) {
    cssRules = { length: 0 };
  }

  if (cssRules.length) {
    console.log('load', e);    
  } else {
    console.error('load error', e);
  }
}`