使用 document.write 异步加载 javascript [英] async loading javascript with document.write

查看:23
本文介绍了使用 document.write 异步加载 javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试异步 google map api javascript.

I am trying to async the google map api javascript.

所以,正常的脚本标签有效<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

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>');

同步模式下的文档对象是HTMLDocument",但异步模式下是#document".页面加载后文档对象发生了一些事情.想法?

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?

干杯.

更新:这个问题更多地是关于为什么不触发 document.write 而不是异步加载谷歌地图 API.如果在这一行设置断点,可以看到 document.write 函数存在.这与 document.write 是原生的有什么关系吗?

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?

推荐答案

document.write 不能从异步脚本调用,因为它与文档分离,因此您的 JS 解析器不会不知道把它放在哪里.充其量,浏览器会忽略它.最坏的情况是,它可能会覆盖当前文档的顶部(就像在文档加载完成后调用 document.write 的情况一样).

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

不幸的是,唯一的答案是重写脚本,这在 google api 的情况下可能不是一个可行的选择.

Unfortunately the only answer is to rewrite the script, which in the case of a google api is probably not a viable option.

这篇关于使用 document.write 异步加载 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆