async loading javascript with document.write

19,668

Solution 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.

Solution 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.

Solution 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

Share:
19,668
user1736525
Author by

user1736525

Updated on June 04, 2022

Comments

  • user1736525
    user1736525 almost 2 years

    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?