How to Prevent Duplicate GMap JavaScript Files from loading on WordPress

If you’re getting errors on websites running WordPress with multiple GMap JavaScript errors, this is one potential fix. Please add this to your child themes function.php.

Plugin manufactures have to do better at not adding GMap files if they’re already loaded, so please report this issue with any plugin makers who fail to check for pre-existing Gmap script tags before adding their own.

Error

You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.

– Javascript console

Fix

This isn’t the best solution, but it generally works. It removes all but the first api from the urls in the $partial_gmap_url array. Please add this to your child-themes functions.php, to resolve most issues.


function de_query_duplicate_gmap_scripts() {
  //go through all the registered & enqued scripts and remove any duplicates with the path

  //customize this with the full path of any files where missing, without the query string (?)
  $partial_gmap_url = [
      1=>'/maps.googleapis.com',
        2=>'/maps.gstatic.com',
        3=>'/maps.google.com',
        4=>'/maps-api-ssl.google.com'
  ];

    global $wp_scripts;
    $wp_scripts->all_deps($wp_scripts->queue);
    $scripts = $wp_scripts->registered;

    $first = true;
    foreach ($scripts as $script) {
        foreach ($partial_gmap_url as $gmap_url) {
            if (strpos($script->src, $gmap_url) !== false) {
                if ($first) {
                    $first = false;
                    continue;
                }
                wp_deregister_script($script->handle);
            }
        }
    }

    $first = true;
    global $wp_styles;
    $wp_styles->all_deps($wp_styles->queue);
    $styles = $wp_styles->registered;
    foreach ($styles as $style) {
        foreach ($partial_gmap_url as $gmap_url) {
            if (strpos($style->src, $gmap_url) !== false) {
              if ($first) {
                $first = false;
                continue;
              }
                wp_deregister_style($style->handle);
            }
        }
    }

}

add_action('wp_enqueue_scripts', 'de_query_duplicate_gmap_scripts', 9999);

Feel free to copy and paste this code to other websites, provide a link back to the source. Feel free to use on your own website.

Leave a Reply