Google Maps Javascript API is supposed to be loaded this way:
<script>
function initMap() {
console.log('loaded');
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
If I had to answer my question, I'd do it like so:
var googleAPILoadedPromise = Promise.pending();
function initMap() {
googleAPILoadedPromise.resolve();
}
googleAPILoadedPromise.promise.then(function() {
console.log('loaded');
});
But deferreds are deprecated and possibly considered an anti-pattern, at least in bluebird. Is there any better way?
On second thought, I'd do it like this:
<script>
var resolvePromise = null;
var promise = new Promise(function(resolve, reject) {
resolvePromise = resolve;
});
promise.then(function() {
console.log('loaded');
});
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=resolvePromise" async defer></script>
Probably like this:
<script>
var loadGoogleMaps = (function(root, d, x, cb){
var s = d.createElement(x)
var a = d.getElementsByTagName(x)[0]
var cleanup = function (done) {
return function (value) {
s.remove()
delete root[cb]
return done(value)
}
}
return new Promise(function (resolve, reject){
root[cb] = cleanup(resolve)
s.onerror = cleanup(reject)
s.async = true
s.src = 'https://maps.googleapis.com/maps/api/js?callback=' + cb
a.parentNode.insertBefore(s,a)
});
})(this, document, 'script', 'googleMapsCallback' + Date.now())
loadGoogleMaps.then(function(){
console.log('loaded')
})
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With