问题描述
我正在动态地将< script>
标记添加到网页的< head>
,而我'我希望能够以某种方式判断加载是否失败 - 404,加载脚本中的脚本错误等等。
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.
在Firefox中,这有效:
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);
但是,这在IE或Safari中不起作用。
However, this doesn't work in IE or Safari.
有没有人知道如何在Firefox以外的浏览器中使用它?
Does anyone know of a way to make this work in browsers other than Firefox?
(我认为不需要放置特殊代码的解决方案在.js文件中是一个很好的。它不够优雅且不灵活。)
(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>
这篇关于如何判断< script>标签无法加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!