-1

I created a script that add javascript files by appending it to the head tag.

Using the code below that I created:

var Dim = (function(s){ 
    var storage; 
    function loadError (oError) {
        throw new URIError("The script " + oError.target.src + " is not accessible.");
    }
    return {
        require : function(script,callback){
            var oScript = document.createElement("script");
            oScript.type = "text\/javascript";
            oScript.onerror = loadError;
            if (callback) { 
                oScript.onload = callback; 
            }
            document.head.appendChild(oScript);
            oScript.src = script;
        }
    };
})();

When we use the script like this:

Dim.require("script.js", function(){alert(token)}); alert(token);

and script.js code is:

alert(" Ok"); var token = " Hello";

The alert(token) throws an error.

Can anyone point me the Problem?

[Question was edited]

MMJM
  • 117
  • 9

1 Answers1

1
Dim.require("script.js", function(){alert(token)}); alert(token);

It runs first alert because its in callback which is called when the script is loaded by the browser.

if (callback) { 
  oScript.onload = callback; 
}

And second is not giving you an alert because it gives you an error

Uncaught ReferenceError: token is not defined

You are loading your script.js asynchronously and while executing second alert , the script.js not loaded yet.

Durga
  • 13,489
  • 2
  • 19
  • 40