Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<link> onerror do not work in IE

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

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?

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

like image 973
marcel Avatar asked May 11 '15 15:05

marcel


1 Answers

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

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


Example using invalid URL:

http://jsfiddle.net/et0g2xg6/


Example using valid URL:

http://jsfiddle.net/et0g2xg6/1

Update August 2017, thanks to @Alex:

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

like image 114
Rick Hitchcock Avatar answered Oct 18 '22 08:10

Rick Hitchcock