Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Handle GET Error (document.createElement)

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

like image 410
Standard Avatar asked Mar 22 '23 04:03

Standard


1 Answers

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);
like image 131
adeneo Avatar answered Apr 23 '23 18:04

adeneo