Checking if external JS library is loaded or not

Attila picture Attila · Feb 17, 2016 · Viewed 8.8k times · Source

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.

Here is my code:

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

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

Answer

hardba11 picture hardba11 · Feb 17, 2016

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

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!