<link> onerror does not work in IE

I am trying to attach an event handler for the onerror event (error 404) to the <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 in Chrome and Opera, but it should work on IE9 + too. I found this one , but I can not find the solution myself.

Is there a way to do this without writing an additional method for dynamically loading styles?

NOTE. I did not mark this question with "jquery", so please do not use it in your answers.

+7
javascript html html5 error-handling
source share
3 answers

In IE, the onerror event onerror not onerror with invalid link urls, but this onload does.

On Chrome, the opposite is true: the onload does not fire with invalid link URLs, but this is an onerror event.

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


Invalid URL example:

http://jsfiddle.net/et0g2xg6/


Valid URL example:

http://jsfiddle.net/et0g2xg6/1

Update August 2017 , thanks @Alex:

onerror triggered by the Chrome browser and Firefox.
onload launched by Internet Explorer.
The edge fails neither onerror nor onload .

+9
source share

The following solution works in Firefox, you just need to organize the function definition and function call:

 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)" /> 
+1
source share

IE When the href link is specified for an invalid domain url, for example. not 404, then IE throws a Access is denied when trying to access the cssRules property.

 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); } }` 
0
source share

All Articles