I need help with a very annoying WordPress issue with external APIs

Prerequisites:

In a WordPress plugin, I need to register and enqueue the external Google Maps API:

wp_register_script(‘mapsapi’, ‘http://maps.googleapis.com/maps/api/js’, array(‘jquery’), ‘3’, true);
wp_enqueue_script(‘mapsapi’);

But:

the users often have a theme or other plugins which ALSO enqueue and register the same Google Maps API, but with another handle (mine is ‘mapsapi’, their handle can be ‘googlemapsapi’ or ‘gmaps’ or however they want to name it)

And sometimes they load the API even from another url: http://maps.google.com/maps/api/js (the url is different, but the API is the same)

THE PROBLEM:

This way, Google Maps API will be included multiple times on user’s page and the maps are not functioning well. Some users have complains about conflicting plugins or a theme conflicting with plugins, thus not working maps.

This is the error thrown in user’s console: “You have included the Google Maps API multiple times on this page. This may cause unexpected errors.”

THE POSSIBLE SOLUTION:

Before I enqueue the maps API, I try to check if the maps API is already enqueued and I try to use the function offered by WordPress: wp_script_is

THE QUESTION:

But: I have to pass as parameter the handle, the name of the script…but how can I know which is the handle used by the theme or by the other plugins for the Google Maps API?

Is there a way I can pass to wp_script_is function a regex string? Or a regex url? Or a simple url?

I really appreciate any help, this drives me crazy since 2014.

For a front end solution, maybe try to collect all the “script” tags, and run a regex on the “src” tag. It should work.

2 Likes

I think you should do some research to find out which one plugin is most used, and using a same name for api.
:smiley:

Thank to @dSKY suggestion, I have found how to realize this inside the PHP plugin file (I made some digging into WP core classes)

Here it is, in case someone needs something similar:

// Check if a certain javascript API is already registered global $wp_scripts; $registered = $wp_scripts->registered; // all registered scripts $api_already_registered = false;
foreach ($registered as $script) {
    // For each script, verify if its src contains 'api_url'
    if (strpos($script->src, 'api_url') !== false) {
        $api_already_registered = true;
    }
}

// Then, just check if( $api_already_registered)

Great, basically the same idea, just for backend. :slight_smile:

Exactly :slight_smile: Thanks again for the idea!