我正在动态地将 <script>
标记添加到页面的 <head>
中,我希望能够判断加载是否以某种方式失败——404,加载脚本中的脚本错误,等等。
在 Firefox 中,这种方法是有效的:
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);
然而,这在 IE 或 Safari 中不起作用。
有没有人知道除了 Firefox 之外的其他浏览器也可以这样工作的方法?
(我不认为需要将特殊代码放在。Js 文件是个不错的选择。它既不优雅又不灵活。)