在“Google+ Sign-In for server-side apps”帮助页面的“第 3 步:在您的页面上包含 Google+ 脚本”中,建议使用以下代码段:
<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
<head>
<!-- BEGIN Pre-requisites -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript">
(function () {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js?onload=start';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
<!-- END Pre-requisites -->
</head>
<!-- ... -->
现在,第二个脚本似乎做了什么:
- 创建一个带有静态源的新 SCRIPT 标签
- 立即将其插入文件中的第一个 SCRIPT 标记之前。
现在,我的问题是什么? 我的意思是,不会这样做:
<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
<head>
<!-- BEGIN Pre-requisites -->
<script async src="https://plus.google.com/js/client:plusone.js?onload=start"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!-- END Pre-requisites -->
</head>
<!-- ... -->
实现同样的目标?为什么这个额外的包装函数插入脚本?
最佳答案
async 属性是一项相当新的开发,大多数版本的 IE 都不支持。 google 的代码本质上是一种模拟异步的跨浏览器方式。
关于javascript - 为什么要动态插入一个静态的JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17996807/