I am trying to async the google map api javascript.
So, the normal script tag works
Do not use document.write()
, for the reasons explained by market and Dr Molle. Use appendChild()
instead, as done in Google's example of async loading.
When you use the parameter callback
inside the script-URL, the script doesn't use write()
and you'll be able to load the API asynchronously.
See: https://developers.google.com/maps/documentation/javascript/tutorial?hl=en#asynch
I just ran into a very similar problem when asynchronously loading amazon ads. I was able to get document.write
approximated in my app for these situations by changing its behavior ($
in this case refers to jQuery):
document.write = function(content) {
if (document.currentScript) {
var src = document.currentScript.src
.replace(/\#.*$/, '')
.replace(/\?.*$/, '')
.replace(/^.*\/\//, '');
setTimeout(function() {
var script = $('script').filter(function() {
var scriptSrc = $(this).attr('src');
return scriptSrc && scriptSrc.indexOf(src) !== -1;
});
$('<div></div>')
.addClass('doc-write')
.html(content)
.insertAfter(script);
}, 0);
} else {
HTMLDocument.prototype.write.apply(document, arguments);
}
};
This approach could be improved on, but it works well enough for my needs. Hopefully you will find it useful.
Adding a comment here since I struggled a fair bit with this problem. When loading the script asynchronously (via a button click for example), make sure you follow the instructions exactly as on the site.
I first got the document.write
error when I didn't give the callback value. And after giving the callback, I got the window.initialize
error because ... duh ... there was no initialize function in my code. I changed that to my function name (something like loadMap) and it started working.
To be honest, just copy the code from the site and it should work. Replace window.onload
with whatever you need to trigger the said function.
document.write
can't be called from an asynchronous script, because it's detached from the document and therefore your JS parser doesn't know where to put it. at best, the browser will ignore it. at worst, it could write over the top of your current document (as in the case of calling document.write after the document has finished loading).
Unfortunately the only answer is to rewrite the script, which in the case of a google api is probably not a viable option.