Att*_*ila 2 jquery google-maps script-tag google-maps-api-3
我当前的设置是用户单击链接以动态加载内容,其中还包括在脚本中加载.我希望能够测试是否加载了外部脚本(特别是Google Maps JS API),如果不加载,那么就这样做.
这是我的代码:
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: log错误中出现此错误
编辑:不再使用传感器参数,因此它已从下面的代码中删除.
如果我理解正确,我认为你可以放弃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);
}
这应该让你有希望.祝好运!