如何在Internet Explorer中触发script.onerror? [英] How to trigger script.onerror in Internet Explorer?

查看:145
本文介绍了如何在Internet Explorer中触发script.onerror?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN上的 onerror页面声明可以将onerror处理程序附加到脚本元素,并且在对象加载期间发生错误时触发。。

The onerror page on MSDN states that the onerror handler can be attached to a script element and that it "Fires when an error occurs during object loading.".

出于单元测试的目的,我是试图让这个onerror处理程序触发,但找不到合适的例子。

For the purpose of unit tests, I am trying to get this onerror handler to fire, but could not find a suitable example.

以下代码在Firefox中触发错误,但在Internet Explorer中没有显示警告

The following code triggers an error in Firefox, but no alert is displayed in Internet Explorer

<script src="http://www.google.com/NOTFOUND.js" onerror="alert('error fired')"></script>

有没有人知道script.src的值会触发附加到script.onerror的处理程序?

Does anyone know a value for script.src that would fire the handler attached to script.onerror?

推荐答案

我发现这是隐藏在一些MSDN文档中


请注意,文档错误地说这适用于元素太;该错误将在3月份Internet Explorer 5最终版本的Workshop文档中修复。

Note that the documentation mistakenly says this works for elements too; the error will be fixed in the Workshop documentation for the final release of Internet Explorer 5 in March.

我接下来想到的是可能有帮助的是onreadystatechange事件:

The next thing I thought of that could help is the onreadystatechange event:

<script src="http://www.google.com/NOTFOUND.js" onreadystatechange="alert(this.readyState)">

这个事件对我来说是两次,一次是加载而另一次是加载,无论是脚本是否有效。我发现的其他文档说,有时它会触发一个完整的事件,并且它应该解雇的时间并不是很清楚。所以它看起来不会起作用。

This event fires twice for me, once with "loading" and again with "loaded", whether the script is valid or not. Other documentation I've found says that sometimes it fires a complete event, and it's not really clear when it's supposed to fire. So it looks like that won't work.

所以我认为你留下了一个hacky解决方案,检查脚本应该声明的变量是否确实存在。在HTML中:

So I think you're left with the hacky solution of checking that a variable which the script is supposed to declare really exists. In HTML:

<script src="http://yourdomain.com/declare_foo.js"></script>
<script>if (typeof foo == "undefined") {alert ('error loading script');}</script>

然后当然在declare_foo.js中,你有

And then of course in declare_foo.js, you'd have

var foo = 'Script loaded successfully';

这篇关于如何在Internet Explorer中触发script.onerror?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆