I wrote a script like that:
NS.load = function(src) {
var script = document.createElement("script").setAttribute("src", src);
document.getElementsByTagName("head")[0].appendChild(script);
}
It loads files but I can’t reach functions and variables defiened in other files.
//js/main.js
var qux = {name: "name"};
NS.load("js/foo.js");
//js/foo.js
alert(qux.name); //undefined variable
But if I define qux like this:
window.qux = {name: "name"};
I can reach qux variable in other modules. As far as I know all globals are already a member of window object. So why I have to define variables like this. Could you offer another method?
Thanks.
It looks like you tried to shortcut your code by calling
createElementandsetAttributeall on 1 line, butsetAttributedoesn’t return anything, so you can’t go callingappendChildon it’s return value, because there is none.This will fix it:Edit:
What sort of environment are you running your code in? Is something happening cross-site or are you defining qux inside of another function? The following works for me, running the files via http://localhost/test.html
foo.js:
I get an alert with “name” when the page loads.