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

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

问题描述

MSDN 上的错误页面 指出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)">

这个事件对我触发了两次,一次是loading",一次是loaded",不管脚本是否有效.我发现的其他文档说有时它会触发一个完整的事件,并且不清楚何时应该触发.所以看起来这行不通.

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天全站免登陆