检查外部JS库是否已加载

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)。这会导致日志中的错误: 日志错误

我真的很困惑,在 $.getScript 的回调函数中,脚本总是被加载,但你正在加载 contact.js 并似乎期望 Google 地图被加载,尽管这两个脚本似乎没有任何关系? - adeneo
你可以从https://dev59.com/PWkw5IYBdhLWcg3w_Pbn找到答案。 - Lumi Lu
@adeneo 如果我让你感到困惑,我很抱歉,因为我只学习了一个月的Web开发 :p 希望这回答了你的问题:contact.js 包含一个函数,需要先加载Google Maps - 这个js文件基本上创建地图,设置其参数等等 - 所以必须先加载Google Maps,否则会出现错误。在调用 contact.js 中的函数之前,我需要同时加载 contact.js 和 Google Maps API。我只想加载一次Google Maps,否则会出现错误(但是在加载 contact.js 时不会出现这样的错误)。 - Attila
1个回答

7

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

如果我理解正确,您可以放弃len的内容,只需检查Google是否已加载...是这样吗? 如果是,请尝试以下方法。

 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);
}

希望这能帮到你。祝你好运!

修复了你的格式! - duncan
1
@hardba11 这太完美了,非常感谢!我删除了“sensor=false”,因为我收到了一个错误,但是即使没有这部分,它仍然完美地工作:“Google Maps JavaScript API不再需要传感器参数。它不会影响Google Maps JavaScript API的正常工作,但我们建议您从脚本元素中删除传感器参数。” 来自这里:https://developers.google.com/maps/documentation/javascript/error-messages - Attila
是的 - 我应该删掉那部分。很高兴能帮到你。感谢您接受答案! - hardba11
它可以工作,我尝试将其与官方的Angular地图组件一起使用。我尝试了类似于'window'中的'google',但它没有成功。它总是说Google库未加载。但是有了这个解决方案,Google地图不会意外地加载两次。 - Samiullah Khan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接