为什么动态插入静态JS?

时间:2013-08-01 14:26:14

标签: javascript

在“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标记
  • 在文件中的第一个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>
<!-- ... -->
实现同样的事情?为什么这个额外的包装函数插入脚本?

1 个答案:

答案 0 :(得分:5)

async属性是一个相当新的开发,大多数IE版本都不支持。谷歌的代码本质上是一种模仿异步的跨浏览器方式。