Search code examples
jqueryhtmlgoogle-mapshtml5-history

Google Maps API included multiple times when reloading the page with AJAX using HTML5 History API


I've got a site that navigates and reloads page information using HTML5 history API. This sends an AJAX call which retrieves the relevant page information. On my 'contact' page I have the google maps api script. If the page is loaded by accessing the URL it works fine. Google loads in the maps API and includes it before my closing body tag.

If I navigate away from the page (using the history API to remove and add content) and then return to the contact page (again through the history API) a second call is made to the (already included) maps API and it doubles it up. This causes the warning message in the console.

I've tried removing the Google Maps script that's added before the closing body tag before the new content is loaded but as the script has been parsed all the relevant functions for the map remains in the browser memory.

So I guess my question is, 'Is there any way to unload all of the google maps JS as I make my AJAX requests for page content?'.

The console message is as follows:

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


Solution

  • I also get this error, I have a page which uses google maps and if I use ajax to reload the part of the page with the google map code the error appears.

    Note that my HTML is not duplicated but a html block is overwritten with the same data having the google maps HTML and it is treated as if it were two blocks not one it seems. I even tried using the jquery .empty() before inserting the html block but no change, still error for multiple. The page does not throw error on load, so my only conclusion is this.

    EDIT: When I think about it I think the reason is that my HTML block contains a script include line and even if this is only one time in the HTML the whole point of this line is loading a bunch of code into the DOM so simply put... Sollution is only loading the script once - just as google says! doh! Just need to think through what those < script src=" lines basically does for the DOM :) So adding a JS block checking if maps api is loaded and only load if it isnt. Think of PHP difference of include() and include_once()