相关疑难解决方法(0)

如何判断<script>标记是否加载失败

我正在动态地向<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文件中放置特殊代码的解决方案是一个很好的解决方案.它不够优雅且不灵活.)

javascript script-tag onerror

103
推荐指数
8
解决办法
12万
查看次数

Internet Explorer中"script"标记的"onload"处理程序

我一直在使用这个函数将onload处理程序附加到脚本标记,它似乎是互联网上推荐的方式.
然而,如果页面已经加载(在8中测试),它在Internet Explorer中不起作用.您可以看到它在普通浏览器中有效(加载脚本时会触发警报).

我错过了什么吗?
谢谢

javascript internet-explorer onload

51
推荐指数
2
解决办法
6万
查看次数