admin管理员组

文章数量:1406926

I'm trying to 'include' a JS file to my document. It works fine, but when the file is offline, it should set a variable to FALSE. I googled it, but I didn't get it. So I tried it with the try/catch:

    try {
      var jq = document.createElement('script');
      //jq.onload = put;
      jq.type = 'text/javascript';
      jq.src = 'http://127.0.0.1:9666/jdcheck.js';
      document.getElementsByTagName('head')[0].appendChild(jq);
    }
    catch(e) {
    console.log('An error has occurred: '+e.message);
        jdownloader = false;

    }

It just throws me the error

  Failed to load resource http://127.0.0.1:9666/jdcheck.js

How is it possible to set the var to FALSE?

Thank you, Markus

I'm trying to 'include' a JS file to my document. It works fine, but when the file is offline, it should set a variable to FALSE. I googled it, but I didn't get it. So I tried it with the try/catch:

    try {
      var jq = document.createElement('script');
      //jq.onload = put;
      jq.type = 'text/javascript';
      jq.src = 'http://127.0.0.1:9666/jdcheck.js';
      document.getElementsByTagName('head')[0].appendChild(jq);
    }
    catch(e) {
    console.log('An error has occurred: '+e.message);
        jdownloader = false;

    }

It just throws me the error

  Failed to load resource http://127.0.0.1:9666/jdcheck.js

How is it possible to set the var to FALSE?

Thank you, Markus

Share Improve this question edited Jun 4, 2014 at 12:04 Raidri 17.6k11 gold badges66 silver badges68 bronze badges asked Oct 4, 2013 at 13:02 StandardStandard 1,5221 gold badge17 silver badges39 bronze badges 3
  • jdownloader will be false when catch clause is executed. what do you want exactly – Rajesh Commented Oct 4, 2013 at 13:06
  • Do you really get an error thrown? Could it be that this is just a warning? For then the catch block will never execute. – Wolfgang Kuehn Commented Oct 4, 2013 at 13:07
  • You may use the onload event on the script tag. If it never fires, then the resource could not be loaded. – Wolfgang Kuehn Commented Oct 4, 2013 at 13:10
Add a ment  | 

1 Answer 1

Reset to default 7

You're sort of doing it wrong. When checking if a script source can be loaded, there are built in onload and onerror events, so you don't need try / catch blocks for that, as those are for errors with script execution, not "404 file not found" errors, and the catch part will not be executed by a 404 :

var jq = document.createElement('script');
jq.onload = function() {
    // script loaded successfully
}

jq.onerror = function() {
    // script error
}

jq.type = 'text/javascript';
jq.src = 'http://127.0.0.1:9666/jdcheck.js';
document.getElementsByTagName('head')[0].appendChild(jq);

本文标签: google chromeJavascript Handle GET Error (documentcreateElement)Stack Overflow