我正在动态地向<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);
Run Code Online (Sandbox Code Playgroud)
但是,这在IE或Safari中不起作用.
有没有人知道如何在Firefox以外的浏览器中使用它?
(我不认为需要在.js文件中放置特殊代码的解决方案是一个很好的解决方案.它不够优雅且不灵活.)