sureshunivers
sureshunivers

Reputation: 1753

How to find a file is available on server in jQuery?

I am trying to load a java script file from another server to my web page using java script code document.write method. like,

document.write("<script type='text/javascript' src='http://www.mydomain.com/js/myscript.js'></script>");

But the respective path does not has the myscript.js so its throw 404 File not found error in browser error console.

How can I predict and avoid this kind of errors?

If possible to predict the error, I will display alternative message instead of calling missed js file functions.

Upvotes: 1

Views: 95

Answers (4)

Anoop
Anoop

Reputation: 23208

Use JavaScript to load script:

function onReadyState() {
    console.error("Unable to load file: "+ this.src + ". Please check the file name and parh.");
    return false;
}  

function addJS(path){
    var e = document.createElement("script");
    e.onerror  = onReadyState;
    e.src = path;
    e.type = "text/javascript";
    document.getElementsByTagName('head')[0].appendChild(e);
}

addJS('http://www.mydomain.com/js/myscript.js');

Upvotes: 2

Anton Baksheiev
Anton Baksheiev

Reputation: 2251

try this approach

   var js="ajax/test.js";

    $.getScript(js) .done(function(script, textStatus) {
          var script = document.createElement( 'script' );
          script.type = 'text/javascript';
          script.src = js;
          document.body.appendChild(script);;
    })

for more details: jQuery.getScript

Please note: Use javascript (not jQuery) to manipulate HTML DOM

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

If the file requested is in your domain (as it seems from the question) just do a previous ajax call (with HEAD method) of that resource and check if the response status is 200 (ok) or 304 (Not modified)

Upvotes: 0

Eugene Naydenov
Eugene Naydenov

Reputation: 7295

Try jQuery.getScript( url [, success(script, textStatus, jqXHR)] ) - you can set success and error handlers in it.

Upvotes: 1

Related Questions