Search code examples
javascriptcssonerror

Which HTML elements support onerror attribute?


I have a site that loads CSS and fonts from Google Web Fonts. However, one place where the site will be used is a local intranet with no Internet access.

I still want to use the fonts from Google where I can for the benefits that Google offers, such as the fonts being downloaded from a CDN and possibly already being cached on the user's computer from visits to another site that uses them.

I also use Google-hosted jQuery and I use the following code (from HTML5 Boilerplate) to load jQuery from my server if Google is not accessible:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.0.min.js"><\/script>')</script>

I am looking for a way to do the same for CSS files.

I have used <img src="..." onerror="..." /> in the past for handling images that don't load, so I was wondering if I can use that for stylesheets that don't load too. I did a quick test in a few browsers, using <link href="..." onerror="..." rel="stylesheet" type="text/css" />, and the onerror was executed in all of them, but I would like to find out if I can expect this to work consistently in all browsers. Or is there a better way to do it?

I saw several other answers here that discuss watching the document.styleSheets collection, but that sounds like much more of a hack than this does.


Note: This is really more of a "is this practical and do people use it"-question than a "what does the spec have to say about it"-question.


Solution

  • I believe the list of supported events on <script> and <link> at pieisgood is what you're looking for.

    As you can see, onload is the most widely supported for <link> which is very lacking in working events. But you could try to implement an error event by having onload clearTimeout for some function that assumes an error happened.