Dynamic Script Tags for JSON requests ... detection if there is an XXX error?

I am making a bunch of json requests with dynamic script tags. Is it possible to determine if there is an error in the request (for example, error 503, error 404) and start something when an error is detected?

+5
source share
7 answers

use ajax instead. AFAIK there is no way to determine if a script tag is loaded or not, and if not, why is it not loading. Using ajax, you can load json and it will tell you why it is not loading.

Using a library such as jQuery becomes very simple:

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script",
  error: function(xhr, error, exception){
    alert(xhr.status); //Will alert 404 if the script does not exist
  }
});
+11
source

AFAIK, - , (, script, ). (, , onerror ) .

, , SOP, XHR, . X-domain XHR.

+4

, , -, XHR?

script , - JSONP, - .

script, . 404, script .

, -, JSONP.

+3

jQuery, jQuery-JSONP, jQuery, <script> , .

, jQuery-JSONP:

  • JSON,
  • , URL-,
  • , ,
  • ( ),
  • , AJAX,
  • -.
+1

, error fileName script. , . , , fileName - Firefox Opera. , , .

, :

var getErrorScriptNode = (function () {
    var getErrorSource = function (error) {
        var loc, replacer = function (stack, matchedLoc) {
            loc = matchedLoc;
        };

        if ("fileName" in error) {
            loc = error.fileName;
        } else if ("stacktrace" in error) { // Opera
            error.stacktrace.replace(/Line \d+ of .+ script (.*)/gm, replacer);
        } else if ("stack" in error) { // WebKit
            error.stack.replace(/at (.*)/gm, replacer);
            loc = loc.replace(/:\d+:\d+$/, "");
        }
        return loc;
    },
    anchor = document.createElement("a");

    return function (error) {
        anchor.href = getErrorSource(error);
        var src = anchor.href,
        scripts = document.getElementsByTagName("script");
        anchor.removeAttribute("href");
        for (var i = 0, l = scripts.length; i < l; i++) {
            anchor.href = scripts.item(i).src;
            if (anchor.href === src) {
                anchor.removeAttribute("href");
                return scripts.item(i);
            }
        }
    };
}());
0

( , ), script.

, 200.

If you have access or not, you can use setTimeout when creating the script tag, passing a function that will throw an error if it expires before the jsonp handler is called. Make sure the jsonp handler is interrupted if an error handler has been called.

You will need to track each request through the global collection, but you will be able to cancel and count the requests. This is similar to how XHR objects are managed by a jQuery type library.

0
source

All Articles