Check whether url returns 404
I'm trying to check whether an URL returns 404, 403 etc when including a Javascript file. It works ok, but I still get an error in "Chrome developer tools".
This is my code:
(function() {
try
{
var ml = document.createElement('script');
ml.type = 'text/javascript';
ml.async = true;
ml.id = 'monoloop_invoke';
ml.onerror = function(){alert('File does not exist');};
ml.src = 'http://somedomain.com/somefile.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ml, s);
}
catch(err)
{
alert('Error: '+err);
}
})
();
If the file does not exist it shows the error "File does not exist" from the ml.onerror
function. This is all good. But the problem is that I still get an error line in my console like:
GET http://somedomain.com/somefi开发者_如何学JAVAle.js 403 (Forbidden)
and the try/catch does not catch this error.
Anyone knows how to solve this? Or is there another way of testing if a URL exists before including it? I cannot use AJAX as I need to use this in a cross-domain fashion. I could use jQuery if necessary.
EDIT: It does not show an error in IE, so i guess this maybe just relates to the way chrome reports issues. Does anyone see a more elegant solution for checking if a file exisists without genreting anything in the console.
jQuery.getScript( url, [ success(data, textStatus) ] )
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
url A string containing the URL to which the request is sent.
success(data, textStatus) A callback function that is executed if the request succeeds.
To catch the errors use the ajaxError event:
http://api.jquery.com/ajaxError/
精彩评论