Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

javascript - How to trigger script.onerror in Internet Explorer?

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.".

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

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>

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found this buried in some MSDN documentation:

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.

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.

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>

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

var foo = 'Script loaded successfully';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...