Loading Google Maps API via AJAX, console error

梦想与她 提交于 2019-12-21 18:05:32

问题


I'm building a fully dynamic website using jquery/javascript, ajax and php.

When I click on a navigation link, the browser opens that page using ajax.

So basically all pages are loaded within the same index.php.

If I go to 'Location' tab, where I have a google map, it will load the Google Maps script dynamically (adding a script tag to the body).

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;callback=initialize"></script>

This script is loaded automatically by the previous script

<script src="https://maps.gstatic.com/maps-api-v3/api/js/19/1/intl/hr_ALL/main.js"></script>

When I leave the 'Location' page, I check if the scripts are present and remove them.

If I go back to 'Location' without refreshing the page, I thought the map would have a clean start, but I get this error in console:

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

Even though the scripts were previously removed, and the map and content changed to something else, I get that error.

Since I know I have only once instance of the map, should I just ignore it?

Or it really has some kind of reference to the old map, and removing the two scripts is just not enough.

Thank you for any information!


回答1:


Removing script-elements will not remove objects that have been created by these scripts( basically it will not have any effect).

Check if the maps-API already has been loaded:

<script>
jQuery(function(){
if(!window.google||!window.google.maps){
  var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3&' +
        'callback=initialize';
    document.body.appendChild(script);
}
else{
  initialize();
}});
</script>


来源:https://stackoverflow.com/questions/27216159/loading-google-maps-api-via-ajax-console-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!