Checking if a URL is broken in Javascript

I’d recommend to use jQuery for correct cross-browser ajax requests:

function UrlExists(url, cb){
    jQuery.ajax({
        url:      url,
        dataType: 'text',
        type:     'GET',
        complete:  function(xhr){
            if(typeof cb === 'function')
               cb.apply(this, [xhr.status]);
        }
    });
}

Usage:

UrlExists('/path/script.pl', function(status){
    if(status === 200){
       // file was found
    }
    else if(status === 404){
       // 404 not found
    }
});

Leave a Comment