使用 JavaScript 动态加载 JavaScript [英] Dynamically load JavaScript with JavaScript
问题描述
经过一个多小时的尝试使其正常工作后,我认为这是因为跨域策略,但我真的认为这会起作用.我也找不到很多关于它的信息.但是,这是我的问题.我有一个名为 http://mysite.com 的网站,然后我包含了一个 3rd 方脚本(我写的)及其在 http://supercoolsite.com/api/script.js 并且这个脚本需要动态加载谷歌地图 api:http://maps.google.com/maps/api/js?sensor=false 在它运行之前.好吧,我认为这段代码会起作用:
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
test
"位于init()
的顶部.所以,它正在加载脚本,但似乎没有执行它.那么,有什么想法吗?如果是跨站点脚本问题,我能想到的解决此问题的唯一方法是在我们端使用 PHP 脚本,该脚本基本上只是将标题设置为文本/javascript 标题,然后 echo 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.
附言我也尝试添加 jQuery,然后执行 getScript()
,但它仍然不起作用
P.S. I also tried adding jQuery, then doing getScript()
, and it still didnt work
-- 更新 --
看到这个小提琴:http://jsfiddle.net/ycMCa/2/
您会在控制台中看到错误消息:Uncaught TypeError: undefined is not a function
You'll see that you get the error in your console:
Uncaught TypeError: undefined is not a function
尽管 google
变量是全局变量.
Despite that the google
variable is global.
推荐答案
你只是有一个小错误:
fileref.onload = callback();
这将立即调用 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屋!