Reputation: 1011
I'm using AJAX to change the content of my pages without refreshing the actual page, therefore the specific scripts and addons for each page do load through AJAX too.
The problem is with Google Maps API, I had to include it in every page, because otherwise it doesn't work, but because of that it shows a console error that it's being loaded multiple times You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
I already know how to check if it's loaded, but I don't know how to prevent it from loading again:
if(google && google.maps){
//Code to prevent loading the addon again
}
How do I prevent loading google maps (or any other addon) more than once?
Upvotes: 1
Views: 812
Reputation: 59328
You could consider to replace static file reference:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
to dynamic one, for example:
function ensureGoogleApi() {
if (typeof google === "undefined" || typeof google.maps === "undefined") {
return $.getScript('https://maps.googleapis.com/maps/api/js');
}
return new $.Deferred().resolve(google.maps);
}
where $.getScript
is used to load Google Maps API
Example
ensureGoogleApi()
.then(function () {
initMap();
});
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
function ensureGoogleApi() {
if (typeof google === "undefined" || typeof google.maps === "undefined") {
return $.getScript('https://maps.googleapis.com/maps/api/js?key');
}
return new $.Deferred().resolve(google.maps);
}
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map"></div>
Upvotes: 1