security - Dynamically load JavaScript with JavaScript -
after on hour of trying work i'm thinking it's because of cross domain policies, thought work. can't find lot of info on either. but, here issue. have site called http://mysite.com , include 3rd party script (what im writing) , @ http://supercoolsite.com/api/script.js , script needs dynamically load google maps api at: http://maps.google.com/maps/api/js?sensor=false before runs. well, figured code work:
function loadscript(filename,callback){ var fileref=document.createelement('script'); fileref.setattribute("type","text/javascript"); fileref.setattribute("src", filename); fileref.onload = callback(); if (typeof fileref!="undefined"){ document.getelementsbytagname("head")[0].appendchild(fileref) } } loadscript('http://maps.google.com/maps/api/js?sensor=false',function(){ console.log('done loading'); init(); });
but response in console is:
api.js:408 done loading api.js:115 test api.js:310 uncaught referenceerror: google not defined
the "test
" @ top of init()
. so, it's loading script, it's not executing it, seems. so, ideas? if cross site scripting issue method of fixing think of having php script on our end sets header text/javascript header , echo file_get_contents()
googlemaps.php
file host. try speak, but, if possible, way pure js awesome.
p.s. tried adding jquery, doing getscript()
, , still didnt work
-- update --
see fiddle: http://jsfiddle.net/ycmca/2/
you'll see error in console: uncaught typeerror: undefined not function
despite google
variable global.
you have minor error:
fileref.onload = callback();
this call callback
, assign return value fileref.onload
.
it should be
fileref.onload = callback;
you should add handler before set source (just in case).
Comments
Post a Comment