Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to detect whether an external javascript file is fully loaded?

Tags:

javascript

I have a web form that uses reCAPTCHA to filter out robots. The form has a <script> tag that loads the captcha challenge in an <iframe>. If this script fails to load, then the captcha challenge would not appear and no one would be able to send a post.

Is there any way that I can detect whether the script is loaded so that I can turn off this feature from my side?

like image 454
Question Overflow Avatar asked May 07 '12 02:05

Question Overflow


3 Answers

Attach the load event to the script element which points to reCAPTCHA.

var script = document.createElement("script");

script.addEventListener("load", function() {
   // Script has loaded.
});

script.src = "/path/to/recaptcha.js";

document.body.appendChild(script);
like image 96
alex Avatar answered Nov 10 '22 10:11

alex


You could probably find a way to do that detection, but I wouldn't recommend it, as it defeats the purpose of the captcha. A computer/robot could easily make the script not load. A hosts file entry would do the trick.

A script could also be made that just executes your handling for the failed to load case, thereby circumventing your captcha.

like image 22
Paul Avatar answered Nov 10 '22 10:11

Paul


script.addEventListener wont work on IE8 and IE7. for that you need to

  if (!script.addEventListener) {
        script.attachEvent("onload", function(){
        // script has loaded in IE 7 and 8 as well.
});
    }
    else
    {
    script.addEventListener("load", function() {
       // Script has loaded.
    });
}
like image 30
ZKK Avatar answered Nov 10 '22 09:11

ZKK