检查是否已加载外部JS库 [英] Checking if external JS library is loaded or not

查看:96
本文介绍了检查是否已加载外部JS库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的设置是让用户单击链接以动态加载内容,其中还包括脚本加载.我希望能够测试是否加载了外部脚本(特别是Google Maps JS API),如果不是,则继续进行操作.

My current set-up has the user click on a link to load content dynamically, which also includes loading in scripts. I want to be able to test whether or not an external script (specifically the Google Maps JS API) is loaded, and if it's not then to go ahead and do so.

这是我的代码:

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).它在日志中导致此错误: 记录错误

However, this does not work. Every time the user clicks to go to the contact page, "len" is always 0, whether or not the script is actually loaded already ( "len" should be more than 0 when it's loaded). It leads to this error in the log: log error

推荐答案

不再使用sensor参数,因此已从下面的代码中将其删除.

The sensor parameter is no longer used so it has been removed from the code below.

如果我理解正确,我认为您可以抛弃len的东西,只是检查google是否已加载...是真的吗?如果是这样,请尝试这个.

If I understand correctly, I think you can ditch the len stuff and just check if google is loaded...is that true? If so try this.

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

这应该使您充满希望.祝你好运!

This should get you going hopefully. Good luck!

这篇关于检查是否已加载外部JS库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆