DigitalZebra
DigitalZebra

Reputation: 41553

What HTTP headers/responses trigger the "onerror" handler on a script tag?

I'm inserting a script tag into the DOM like so (think JSONP):

var s = document.createElement('script');
s.src = "http://abc.com/js/j.js";
s.onerror = function() {
   alert("Error loading script tag!");
};
document.getElementsByTagName('head')[0].appendChild(s);

Now, I know a 404 response from abc.com for the script above would trigger that event... What other headers/responses would cause the script tag to throw an error? I'd imagine it varies a little bit by browser, but if anyone has any sort of list that would be very helpful.

Thanks!

Upvotes: 6

Views: 1339

Answers (1)

Nikolay Yordanov
Nikolay Yordanov

Reputation: 1404

4xx and 5xx should result in an error - at least they are defined as error codes.

[edit] Just tested it in Fx 3.5 - that's the correct statement.

Here's the test code if you want to test other browsers (quick and dirty...)

var codes = [100, 101, 102, 122, 200, 201, 202, 203, 204, 205, 206, 207, 226, 300, 301, 302, 303, 304, 305, 306, 307, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410], 411, 411, 412, 413,414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 444, 449, 450, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510 ];

            $(codes).each(function() {
                var s = document.createElement('script');
                s.src = "http://localhost/test.php?code="+this;
                var cd = this;
                s.onerror = function() {
                    document.write(cd+',')
                };
                document.getElementsByTagName('head')[0].appendChild(s);

            });

And php code:

<?php header('HTTP/1.0 '.$_GET['code'].' OK'); ?>

Upvotes: 7

Related Questions