12

I am trying to async the google map api javascript.

So, the normal script tag works <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

But, the following async version doesn't.

(function () {
    var gmap = document.createElement('script'); gmap.type = 'text/javascript'; gmap.async = true;
    gmap.src = 'https://maps.googleapis.com/maps/api/js?sensor=false';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gmap, s);
})();

After some breakpoint+inspect action, I found out that this line doesn't run properly in the async mode.

document.write('<' + 'script src="' + src + '"' + 
' type="text/javascript"><' + '/script>');

The document object in the sync mode is a "HTMLDocument", but in the async mode is a "#document" instead. Something happened to the document object after the page is loaded. Thoughts?

Cheers.

Update: this question is more about why document.write is not fired rather than async load the google map api. If you set a breakpoint on this line, you can see document.write function exists. Does this have anything to do with the fact that document.write is native?

user1736525
  • 1,119
  • 1
  • 10
  • 15

5 Answers5

8

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.

market
  • 473
  • 1
  • 4
  • 9
  • Thanks. I did breakpoint on this line and try to document.write myself. It did find the write() function and that's why it's weird. If the write function is detached, then why is it not undefined? – user1736525 Oct 22 '12 at 03:39
8

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.

2

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

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • yeah, I had the callback but I ran into another problem in jquery mobile, where it's loading google map api multiple times. I didn't like the warning message. – user1736525 Oct 22 '12 at 03:32
  • 2
    When you don't like the warning don't load the API multiple times. – Dr.Molle Oct 22 '12 at 08:26
  • It's jquery mobile in asp mvc using the jqm ajax mode. So it just seem cleaner to load the API once rather than using the jqm events. – user1736525 Oct 22 '12 at 09:11
0

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.

Marcelo
  • 9,387
  • 3
  • 35
  • 40
0

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.

Plasty Grove
  • 2,807
  • 5
  • 31
  • 42