Why isn't my JavaScript function able to access global-scope functions/variables defined in my other .js files? -
i wrote script that:
ns.load = function(src) {     var script = document.createelement("script").setattribute("src", src);     document.getelementsbytagname("head")[0].appendchild(script); }   it loads files can't reach functions , 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 define qux this:
window.qux = {name: "name"};   i can reach qux variable in other modules. far know globals member of window object. why have define variables this. offer method?
thanks.
it looks tried shortcut code calling createelement , setattribute  on 1 line, setattribute doesn't return anything, can't go calling appendchild on it's return value, because there none.this fix it:
ns.load = function(src) {     var script = document.createelement("script");     script.setattribute("src", src)     document.getelementsbytagname("head")[0].appendchild(script); }   edit:
what sort of environment running code in? happening cross-site or defining qux inside of function? following works me, running files via http://localhost/test.html
<html> <head>     <script type="text/javascript">         load = function(src) {             var script = document.createelement("script");             script.setattribute("src", src);             document.getelementsbytagname("head")[0].appendchild(script);         }         var qux = {name: "name"};         load("foo.js");     </script> </head> <body></body> </html>   foo.js:
alert(qux.name);   i alert "name" when page loads.
Comments
Post a Comment