0

In my code I am loading a script from a remote server. Here is what I have done:

var loadFlag = false;
var myWidgetScript = document.createElement("script");
myWidgetScript.type = "text/javascript";
myWidgetScript.charset = "utf-8";

myWidgetScript.src = document.location.protocol+ "//mytest.com/loader";
document.getElementsByTagName("head")[0].appendChild(myWidgetScript);
myWidgetScript.onreadystatechange=myWidgetScript.onload = myWidgetScript.onload = function() {
loadFlag = true;
if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
        //Do what you want
     }
};
if(!loadFlag){
    alert("Not loaded");
}

Now I want to generate an alert if script tag has failed to load from the URL. I am incase the URL has a typo or if the server mytest.com is down. But in my code it is generating alert even if the URL is correct and server is up... What is wrong with my code?... Can I have some other way to accomplish this..?

Tariq
  • 2,489
  • 11
  • 36
  • 61
  • Is there any variable of External JS which you're going to use? – dikesh Apr 14 '14 at 09:14
  • No, But the external JS is going to use my variables. These variables are going to be in `//Do what you want` area... – Tariq Apr 14 '14 at 09:16

1 Answers1

0

Try this... May be it will help.

var headTag = document.getElementsByTagName("head")[0];

        var jqTag = document.createElement('script');
        jqTag.type = 'text/javascript';
        jqTag.src = 'YOUR SCRIPT';

        headTag.appendChild(jqTag);

if (jqTag)
        {
        if (jqTag.readyState)
        {
            // For old versions of IE
            jqTag.onreadystatechange = function()
            {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                alert('loaded');
            }
            };
        }
        else
        {
            // Other browsers
            jqTag.onload = function() {
            alert('loaded');
            };
        }
        }
dikesh
  • 2,977
  • 2
  • 16
  • 26
  • The problem to address is not that script is loaded or not. The problem to address is that whether URL is accessible or not..! – Tariq Apr 14 '14 at 09:30
  • How about this? http://stackoverflow.com/questions/5344145/how-to-get-response-status-code-from-jquery-ajax – dikesh Apr 14 '14 at 09:44