How to tell if a tag failed to load

UPDATE 2021:
All browsers today support onerror="" on script tags, examples:

  • Building script tag in js on MDN
  • Html example by @Rudey in comments: <script src="nonexistent.js" onerror="alert('error!')"></script>

Original comment from 2010:

If you only care about html5 browsers you can use error event.

From the spec:

If the src attribute’s value is the
empty string or if it could not be
resolved, then the user agent must
queue a task to fire a simple event
named error at the element, and
abort these steps.

(…)

If the load resulted in an error (for
example a DNS error, or an HTTP 404
error) Executing the script block must
just consist of firing a simple event
named error at the element.

This means you don’t have to do any error prone polling and can combine it with async and defer attribute to make sure the script is not blocking page rendering:

The defer attribute may be specified
even if the async attribute is
specified, to cause legacy Web
browsers that only support defer (and
not async) to fall back to the defer
behavior instead of the synchronous
blocking behavior that is the default.

More on http://www.w3.org/TR/html5/scripting-1.html#script

Leave a Comment