动态加载JavaScript的使用JavaScript [英] Dynamically load JavaScript with JavaScript
问题描述
在试图得到它的工作我想这是因为跨域的政策,但我真的认为这会工作一小时后。我也不能找到很多关于它的信息的。但是,这里是我的问题。我有一个名为 http://mysite.com 网站,然后我有一个第三方的脚本(什么即时通讯写作)及其在 http://supercoolsite.com/api/script.js 这个脚本需要动态地加载 http://maps.google.com/maps/api:谷歌的在地图API / JS?传感器,然后再运行=假。好吧,我想通了这code将工作:
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
在测试
是在初始化的顶部()
。因此,它的加载脚本,但它没有执行它,它似乎。因此,任何想法?如果它是一个跨站点脚本问题我唯一的解决这个方法我能想到的是对我们的结束一个PHP脚本,基本上只是设置头文字/ JavaScript的标题,然后回声的file_get_contents()
到 googlemaps.php
文件中,我们的主机。关于如果可能的话试试这个,因为我们说话,但是,一种方式用纯JS做这将是真棒。
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。我也尝试添加了jQuery,然后做 getScript加入()
,它仍然没有工作。
P.S. I also tried adding jQuery, then doing getScript()
, and it still didnt work
- 更新 -
看到这个小提琴:
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.
推荐答案
您只是有一个小错误:
fileref.onload = callback();
这将调用回调
立即转让其返回值以 fileref.onload
This will call callback
immediately and assign its return value to fileref.onload
.
这应该是
fileref.onload = callback;
您将源(以防万一)之前还应该添加的处理程序。
You also should add the handler before you set the source (just in case).
这篇关于动态加载JavaScript的使用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!