2016-02-17 66 views
1

我目前的设置有一个链接,在用户点击动态加载的内容,其中还包括在脚本加载检查。我希望能够测试是否加载了外部脚本(特别是Google Maps JS API),如果不是,则继续前进。如果外部JS库加载与否

这里是我的代码:

if(_href == "contact.html") { 

// this will run everytime we navigate/click to go to "contact.html" 
console.log("contact.html loaded"); 

// load the contact.js script, and once loaded, 
// run the initMap function (located inside contact.js) to load the map 
$.getScript("contact.js", function() { 

    // store the length of the script, if present, in a varialbe called "len" 
    var len = $('script[src="https://maps.googleapis.com/maps/api/js"]').length; 
    console.log(len); 

    // if there are no scripts that match len, then load it 
    if (len === 0) { 
     // gets the script and then calls the initMap function to load the map 
     $.getScript("https://maps.googleapis.com/maps/api/js", initMap); 
     console.log("Google Maps API loaded") 
    } else { 

     // otherwise the script is already loaded (len > 0) so just run the initMap function 
     initMap(); 
    } 
}); 

但是,这是行不通的。每当用户点击去接触网页时,“LEN”始终为0,该脚本是否被实际加载已经(“LEN”时,它的加载应大于0)。它会导致日志中出现此错误: log error

+0

我真的很困惑,回调'$ .getScript'脚本总是加载,但你装'contact.js'和似乎期望谷歌地图被加载,即使这两个脚本唐彼此似乎没有任何关系? – adeneo

+0

你可以找到http://stackoverflow.com/questions/9521298/verify-external-script-is-loaded – user86745458

+0

答案@adeneo对不起,如果我让你感到困惑,但我只学习web开发的一个月现在:p我希望这可以回答你的问题:'contact.js'包含一个函数,它需要首先加载谷歌地图 - 这个js文件基本上创建地图,设置其参数等 - 所以这是必须的谷歌地图第一加载,否则我会得到一个错误。在我调用contact.js中的函数之前,我需要加载contact.js和Google Maps API。我只希望谷歌地图加载一次,否则我得到一个错误(但是,我没有得到任何这样的错误而载入'contact.js' – Attila

回答

3

编辑:传感器参数不再使用,因此它已从下面的代码中删除。

如果我理解正确的话,我觉得你可以沟LEN的东西,只是检查,如果谷歌被加载......是真的吗?如果是这样的话。

if (typeof google === 'object' && typeof google.maps === 'object') { 

    initMap(); 

} else { 

    var script = document.createElement("script"); 

    script.type = "text/javascript"; 

    script.src = "http://maps.google.com/maps/api/js?callback=initMap"; 

    document.body.appendChild(script); 
} 

这应该让你有希望。祝你好运!

+0

修复您的格式! – duncan

+1

@ hardba11这是完美的,太感谢你了!我删除了“sensor = false”,因为我收到了一个错误,但它仍然完美无缺: “Google地图JavaScript API不再需要传感器参数,它不会阻止Google Maps JavaScript API正常工作,但我们建议您从脚本元素中删除传感器参数。“ 从这里开始:https://developers.google.com/maps/documentation/javascript/error-messages – Attila

+0

是的 - 我应该切碎那部分。它帮助你。谢谢你接受答案! – hardba11