I just notice a weird behavior when dynamically loading scripts with AJAX. I intentionally have a misspelled code that throws an error when it is parsed. Even though the Chrome's console indeed shows the error, the AJAX fail handler is never called.
This is the function that I use to load files:
var load_source = function (path) {
/* Variable used to determine whether the request was successful */
var success = false,
failed;
$.ajax(
{
url: path,
async: false,
dataType: 'script',
method: 'GET'
}
).
done(function () {
success = true;
}).
fail(function (xhr, status, error) {
failed = error.stack ? error.stack : error;
});
if (failed)
{
throw new Error('Unable to load JS file {0}: {1}'.format(path, failed));
}
}
The only variable provided to the load_source function is "path", which value is a string with the location and name of such a file: "js/myFile.js".
The misspelled part (the part with a typo) of the script to load is this:
var f = function (arg) {
var param1 = 3,
param2, /* NOTICE the typo: there is a comma instead of a semicolon */
if (param1 > arg)
{
return true;
}
// And more code is coming next...
If I look at the Chrome's console, it shows the error:
Uncaught SyntaxError: Unexpected token if
So far the only way I can catch the error is with the window's onerror event.
So, if that is the only way to catch the error, could you tell me how to stop the "coding" flow, I mean, whenever I call load_source that throws an error (which is handled by the window's onerror function) I want the script to do nothing else:
load_source('js/myFile.js'); // This script will throw the "Uncaught SyntaxError: Unexpected token if" error.
// So I don't want the following code to be executed.
sum(4, 3);
mul(5, 5);
// ...
Can you guys tell me how make the fail event to be triggered?
I also tried with " $(document).ajaxError" but with the same results.