Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

google maps api 3 - async loading javascript with document.write

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...