async loading javascript with [removed]

2019-01-09 15:39发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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



回答4:

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.



回答5:

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.