Dynamically load JavaScript with JavaScript

2019-02-24 02:01发布

问题:

After over an hour of trying to get it to work I'm thinking it's because of cross domain policies, but I really thought this would work. I can't find a lot of info on it either. But, here is my issue. I have a site called http://mysite.com and then I include a 3rd party script (what im writing) and its at http://supercoolsite.com/api/script.js and this script needs to dynamically load the google maps api at: http://maps.google.com/maps/api/js?sensor=false before it runs. Well, i figured this code would 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 my response in my console is:

api.js:408 done loading
api.js:115 test
api.js:310 Uncaught ReferenceError: google is not defined

the "test" is at the top of the init(). So, it's loading the script, but it's not executing it, it seems. So, any ideas? If it is a cross site scripting issue my only method of fixing this i could think of is having a PHP script on our end that basically just sets the header to a text/javascript header and then echo file_get_contents() into a googlemaps.php file we host. About to try this as we speak, but, if possible, a way to do it with pure JS would be awesome.

P.S. I also tried adding jQuery, then doing getScript(), and it still didnt work

-- UPDATE --

See this fiddle: http://jsfiddle.net/ycMCa/2/

You'll see that you get the error in your console: Uncaught TypeError: undefined is not a function

Despite that the google variable is global.

回答1:

You just have a minor error:

fileref.onload = callback();

This will call callback immediately and assign its return value to fileref.onload.

It should be

fileref.onload = callback;

You also should add the handler before you set the source (just in case).

DEMO