异步加载JavaScript文件撰写与 [英] async loading javascript with document.write

查看:116
本文介绍了异步加载JavaScript文件撰写与的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想异步的谷歌地图API的JavaScript。

I am trying to async the google map api javascript.

所以,正常的脚本标签工作原理<脚本SRC =htt​​ps://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?

干杯。

更新:这个问题更多的是文件撰写为什么不开除,而不是异步加载谷歌地图API。如果你在这一行设置一个断点,你可以看到的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?

推荐答案

文件撰写无法从异步脚本调用,因为它是从文档中分离并因此,你的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).

不幸的是,唯一的答案是重写剧本,这在谷歌API的情况下,可能不是一个可行的选择。

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

这篇关于异步加载JavaScript文件撰写与的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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