I'm dynamically adding <script>
tags to a page's <head>
, and I'd like to be able to tell whether the loading failed in some way -- a 404, a script error in the loaded script, whatever.
In Firefox, this works:
var script_tag = document.createElement('script');
script_tag.setAttribute('type', 'text/javascript');
script_tag.setAttribute('src', 'http://fail.org/nonexistant.js');
script_tag.onerror = function() { alert("Loading failed!"); }
document.getElementsByTagName('head')[0].appendChild(script_tag);
However, this doesn't work in IE or Safari.
Does anyone know of a way to make this work in browsers other than Firefox?
(I don't think a solution that requires placing special code within the .js files is a good one. It's inelegant and inflexible.)
There is no error event for the script tag. You can tell when it is successful, and assume that it has not loaded after a timeout:
<script type="text/javascript" onload="loaded=1" src="....js"></script>